Python: using comprehensions in for loops -
i'm using python 2.7. have list, , want use loop iterate on subset of list subject condition. here's illustration of i'd do:
l = [1, 2, 3, 4, 5, 6] e in l if e % 2 == 0: print e which seems me neat , pythonic, , lovely in every way except small matter of syntax error. alternative works:
for e in (e e in l if e % 2 == 0): print e but ugly sin. there way add conditional directly loop construction, without building generator?
edit: can assume processing , filtering want perform on e more complex in example above. processing doesn't belong 1 line.
what's wrong simple, readable solution:
l = [1, 2, 3, 4, 5, 6] e in l: if e % 2 == 0: print e you can have amount of statements instead of simple print e , nobody has scratch head trying figure out does.
if need use sub list else (not iterate on once), why not construct new list instead:
l = [1, 2, 3, 4, 5, 6] even_nums = [num num in l if num % 2 == 0] and iterate on even_nums. 1 more line, more readable.
Comments
Post a Comment