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

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -