I have a problem to understand this code
def get_device_sensors(device_id):
return [elm["sensor"] for elm in db.DB.query("select * from data ",
(device_id,))]
I'm new in python. I don't know what does elm["sensor"]
mean.
Does it mean?:
for elm in db.DB.query("select * from data ")
return elm['sensor']
It means exactly the same as:
results = []
for elem in db.DB.query("SELECT * FROM data", (device_id,)):
results.append(elem['sensor'])
return results
This is a list comprehension , like @khelwood noted, which means you are constructing a list from something you can iterate over.
To summarise:
[ <operation> for <values> in <iterable> ]
basically is a shorthand for:
accumulator = []
for <values> in <iterable>:
accumulator.append(<operation>)
# accumulator contains the result now.
<operation>
usually does something with <values>
, but it may also be a constant or just the <values>
itself.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.