简体   繁体   English

将循环更改为Python列表理解

[英]Change Loop to Python List Comprehension

There is a list of objects, "games." 有一个对象列表,“游戏”。 How can I check to see if the object has an attribute set, and if it doesn't, set the attribute.... using list comprehensions? 如何检查对象是否具有属性集,如果没有,请使用list comprehensions设置属性....

for g in games:
        if not g.score_ratio_h1: g.score_ratio_h1 = avg_score_ratio_h1

This is not a good case for using list comprehensions, in fact: it's very anti-Pythonic . 事实上,这不是使用列表推导的好例子: 它非常反Pythonic The loop doesn't result in the creation of a new list of values, it's just a sequence of assignments. 循环不会导致创建新的值列表,它只是一系列赋值。 Better stick to using a loop, it's fine as it is. 最好坚持使用循环,它很好。 Only if your code looked like this: 只有你的代码看起来像这样:

ans = []
for g in games:
    if not g.score_ratio_h1:
        ans.append(g.score_ratio_h1) # we're appending the results

... Then it'd be a good idea to use comprehensions. ......那么使用理解是个好主意。 But currently the core of the loop is an assignment: 但目前循环的核心是一个任务:

g.score_ratio_h1 = avg_score_ratio_h1

And no useful value returns of that, it's a modification operation (a "side effect") that doesn't get collected anywhere. 并没有有用的值返回,它是一个不会在任何地方收集的修改操作(“副作用”)。 Comprehensions are not meant to be used in such cases. 在这种情况下,并不打算使用理解。 Even more: trying to do an assignment inside a comprehension will result in an error, for example: 更多:尝试在理解中进行分配将导致错误,例如:

lst = [[0], [0], [0]]
[a[0] = 1 for a in lst]
      ^
SyntaxError: invalid syntax

well you can do something like this that uses list comprehension: 你可以做这样的事情,使用列表理解:

for g in (g for g in games if not g.score_ratio_h1):
    g.score_ratio_h1 = avg_score_ratio_h1

it may be perhaps a bit faster... but strange :) 它可能有点快......但很奇怪:)

EDIT: 编辑:

I agree with the two comments, however it may not be completely wasteful depending on the "if" condition, here an example: 我同意这两条评论,但根据“if”条件,这可能并不完全是浪费,这里有一个例子:

  lst = [0 for _ in xrange(708)]
  for i in xrange(100000000):
      if i**2 < 500000:
          lst[i] += i

time: 时间:

real    0m12.906s
user    0m12.876s
sys     0m0.008s

versus: 与:

lst = [0 for _ in xrange(708)]
for i in (i for i in xrange(100000000) if i**2 < 500000):
    lst[i] += i

time: 时间:

real    0m8.857s
user    0m8.792s
sys 0m0.016s

I guess that depending on the condition, and the size of the loop this may be indeed wasteful, but in sometimes it may help to play around list comprehension, even in this case. 我想这取决于条件和循环的大小,这可能确实是浪费,但有时它可能有助于解决列表理解,即使在这种情况下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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