map function python3 to get message length - python-3.x

I was learning the map function,
I was trying to get the message length by using map().
my code is
messages['length'] = messages['message'].map(lambda text: len(text))
But I am not sure since I read the map ducument map(functions, list)
The code above, should I include the list?
Thanks guys

map() is a function, and not a method. That means some_object.map(some_function) isn't valid syntax.
The proper call would be:
messages['length'] = map(len, messages['message'])

Related

Is there an easy way to use glom to get an unknown key from a dictionary?

Is there an easy way to use glom to get an unknown key from a dictionary?
the ??? represents random data that I am trying to capture from an API
book = {"???":[{ "globalIdenity":208565940},{"globalIdenity":228049454}]}
spec =
output_data = glom(book, spec)
print(output_data)
Use an iterator for values then use the next call to get the value
book = {"???":[{ "globalIdenity":208565940},{"globalIdenity":228049454}]}
result = next(iter(book.values()))
print(result)
#output
[{'globalIdenity': 208565940}, {'globalIdenity': 228049454}]

Function prints None when i call it using dictionary

I made a dictionary switcher as follows:
switcher={
0:linked_list,
1:queue,
2:stack
}
and I used switcher[key]() to just call a function.
The function runs as normal but the issue is it prints None before
taking input in while loop of my called function, in this case linked_list()
while(c!=2):
c=int(input(print("Enter operation\n1.Insert beg\n2.Exit")))
if c==1:
some code
I have tried using a return statement and lambda but still it prints None.Also I am not printing the given function.
Because what you are trying to write to the standard output is not your menu seen as a string but the object resulting from the print function.
print function is useless. Argument sent to input function is by default written to the standard output.
Therefore:
while(c!=2):
c=int(input("Enter operation\n1.Insert beg\n2.Exit\n"))
if c == 1:
some code
is enough (with an extra newline after Exit option for more readibility).
See here official documentation about input function.

Itertool.product at to string

Hi I starting learning python.
I have to do a small work to generate password using itertool. the only thing I don't understand how to convert this result :
itertools.product object at 0x03493BE8
to something readeable.
How can I convert it to get a string or something similar ?
Here is my code :
for CharLength in range(12):
words= (itertools.product(Alphabet, repeat=CharLength))
print(words)
itertools.product() returns a generator.
To print them you can use the * operator.
for char_len in range(12):
words = itertools.product(alphabet, repeat=char_len)
print(*words)
itertools.product returns a generator object. If you wish, you could go over it and convert it to a list so it's easier to view its contents, e.g. by using a list comprehension:
words = [w for w in itertools.product(Alphabet, repeat=CharLength)]

Proper Syntax for List Comprehension Involving an Integer and a Float?

I have a List of Lists that looks like this (Python3):
myLOL = ["['1466279297', '703.0']", "['1466279287', '702.0']", "['1466279278', '702.0']", "['1466279268', '706.0']", "['1466279258', '713.0']"]
I'm trying to use a list comprehension to convert the first item of each inner list to an int and the second item to a float so that I end up with this:
newLOL = [[1466279297, 703.0], [1466279287, 702.0], [1466279278, 702.0], [1466279268, 706.0], [1466279258, 713.0]]
I'm learning list comprehensions, can somebody please help me with this syntax?
Thank you!
[edit - to explain why I asked this question]
This question is a means to an end - the syntax requested is needed for testing. I'm collecting sensor data on a ZigBee network, and I'm using an Arduino to format the sensor messages in JSON. These messages are published to an MQTT broker (Mosquitto) running on a Raspberry Pi. A Redis server (also running on the Pi) serves as an in-memory message store. I'm writing a service (python-MQTT client) to parse the JSON and send a LoL (a sample of the data you see in my question) to Redis. Finally, I have a dashboard running on Apache on the Pi. The dashboard utilizes Highcharts to plot the sensor data dynamically (via a web socket connection between the MQTT broker and the browser). Upon loading the page, I pull historical chart data from my Redis LoL to "very quickly" populate the charts on my dashboard (before any realtime data is added dynamically). I realize I can probably format the sensor data the way I want in the Redis store, but that is a problem I haven't worked out yet. Right now, I'm trying to get my historical data to plot correctly in Highcharts. With the data properly formatted, I can get this piece working.
Well, you could use ast.literal_eval:
from ast import literal_eval
myLOL = ["['1466279297', '703.0']", "['1466279287', '702.0']", "['1466279278', '702.0']", "['1466279268', '706.0']", "['1466279258', '713.0']"]
items = [[int(literal_eval(i)[0]), float(literal_eval(i)[1])] for i in myLOL]
Try:
import json
newLOL = [[int(a[0]), float(a[1])] for a in (json.loads(s.replace("'", '"')) for s in myLOL)]
Here I'm considering each element of the list as a JSON, but since it's using ' instead of " for the strings, I have to replace it first (it only works because you said there will be only numbers).
This may work? I wish I was more clever.
newLOL = []
for listObj in myLOL:
listObj = listObj.replace('[', '').replace(']', '').replace("'", '').split(',')
newListObj = [int(listObj[0]), float(listObj[1])]
newLOL.append(newListObj)
Iterates through your current list, peels the string apart into a list by replace un-wanted string chracters and utilizing a split on the comma. Then we take the modified list object and create another new list object with the values being the respective ints and floats. We then append the prepared newListObj to the newLOL list. Considering you want an actual set of lists within your list. Your previously documented input list actually contains strings, which look like lists.
This is a very strange format and the best solution is likely to change the code which generates that.
That being said, you can use ast.literal_eval to safely evaluate the elements of the list as Python tokens:
>>> lit = ast.literal_eval
>>> [[lit(str_val) for str_val in lit(str_list)] for str_list in myLOL]
[[1466279297, 703.0], [1466279287, 702.0], [1466279278, 702.0], [1466279268, 706.0], [1466279258, 713.0]]
We need to do it twice - once to turn the string into a list containing two strings, and then once per resulting string to convert it into a number.
Note that this will succeed even if the strings contain other valid tokens. If you want to validate the format too, you'd want to do something like:
>>> def process_str_list(str_list):
... l = ast.literal_eval(str_list)
... if not isinstance(l, list):
... raise TypeError("Expected list")
... str_int, str_float = l
... return [int(str_int), float(str_float)]
...
>>> [process_str_list(str_list) for str_list in myLOL]
[[1466279297, 703.0], [1466279287, 702.0], [1466279278, 702.0], [1466279268, 706.0], [1466279258, 713.0]]
Your input consists of a list of strings, where each string is the string representation of a list. The first task is to convert the strings back into lists:
import ast
lol2 = map(ast.literal_eval, mylol) # [['1466279297', '703.0'], ...]
Now, you can simply get int and float values from lol2:
newlol = [[int(a[0]), float(a[1])] for a in lol2]

Generate a list from another list transforming each element on Groovy

I've got the following code on a Controller
def db = new Sql(dataSource)
def rawLines = db.rows("SELECT name FROM LINES")
def lines = []
/*(db.rows returns the values as [NAME:value] */
rawLines.each {
lines.add(it.name)
}
/*Then, use lines */
I can't keep away the impression that there is probably some way to do this in a more elegant way, something similar to a list comprehension in Python:
lines = [ l.name for l in db.rows("SELECT name FROM LINES") ]
Having to declare an empty list and then populate it doesn't seem the best way of doing things...
Is it possible to do something like this, or Groovy doesn't allow it?
Can't you just use the spread operator, and do:
lines = rawLines*.name
(see http://docs.groovy-lang.org/latest/html/documentation/index.html#_spread_operator)
tim_yates' answer is a clean solution when you want to call a method (or property) on each element of list in order to transform it e.g.:
[1,2,3]*.multiply(5)
but if you want to call a method from another object or do something more complex you can use collect:
[1, 2, 3].collect {Math.cos(it * Math.PI)}
Well, If you are using grails, why aren't you simply using the a model class together with the findAll method?
Using plain raw SQL should be done on exceptional cases.

Resources