python - if i!=0 in list comprehension gives syntax error -


this question like: if/else in python's list comprehension? , simple syntax error in python if else dict comprehension . still dont understand error make here:

[i if i!=0 in range(2)]              ^        syntax error 

i want entries in list non-zero sparsity.

move if end. refer the python docs entry on list comprehensions.

>>> [i in range(2) if i!=0] # or [i in range(2) if i] [1] 

if looking conditional expression, @martijn pointed out,

>>> [i if i!=0 else -1 in range(2)] [-1, 1] 

if want non 0 entities, filter(...) list.

>>> filter(none, [1, 2, 0, 0, 4, 5, 6]) [1, 2, 4, 5, 6] 

Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -