简体   繁体   中英

Python list comprehension syntax error

Using a for loop, the following python code works.

for item in results:
    item ['currentservertime'] = int(time.time())

I would like to do it with a list comprehension however. So I have tried the following, but i get a syntax error on the =

item['currentservertime'] = int(time.time()) for item in results

where am i going wrong?

A list comprehension won't work here, since you're not at any time building a list - you are changing values in various dictionaries. A list comprehension would be the right tool if your original code was of the form:

currentservertime = []
for item in results:
    currentservertime.append(int(time.time())

Which would translate into the list comprehension:

currentservertime = [int(time.time()) for item in results]

As it stands, your existing loop is the clearest and most direct way to implement what you're doing.

[i.update({'currentservertime': int(time.time())}) for i in results]

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM