简体   繁体   中英

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?

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 . 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:

  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.

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