if i!=0 in list comprehension gives syntax error

拈花ヽ惹草 提交于 2019-12-20 01:11:50

问题


This question is very much like: if/else in Python's list comprehension? and Simple syntax error in Python if else dict comprehension . But still i dont understand what error I make here:

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

I only want the entries in the list that are non-zero for sparsity.


回答1:


Move the if to the end. Refer to The Python Docs entry on List Comprehensions.

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

If you were looking for a conditional expression, you could do something like @Martijn pointed out,

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

If you just want the non zero entities, you could also filter(...) your list.

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



回答2:


The if predicate comes after the specification of the for i in range(2) in a list comprehension. You can also have arbitrary number of ifs.




回答3:


Switch the if i!=0 and for i in range(2) parts:

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


来源:https://stackoverflow.com/questions/18260700/if-i-0-in-list-comprehension-gives-syntax-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!