[英]Python list comprehension syntax error
Using a for loop, the following python code works. 使用for循环,以下python代码有效。
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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.