问题
I have a simple list.
>>> a = [0, 1, 2]
I want to make a new list from it using a list comprehension.
>>> b = [x*2 for x in a]
>>> b
[0, 2, 4]
Pretty simple, but what if I want to operate only over nonzero elements?
'if' needs 'else' in list comprehensions, so I came up with this.
>>> b = [x*2 if x != 0 else None for x in a]
>>> b
[None, 2, 4]
But the desirable result is.
>>> b
[2, 4]
I can do that this way
>>> a = [0, 1, 2]
>>> def f(arg):
... for x in arg:
... if x != 0:
... yield x*2
...
>>> list(f(a))
[2, 4]
or using 'filter' and a lambda
>>> a = [0, 1, 2]
>>> list(filter(lambda x: x != 0, a))
[1, 2]
How do I get this result using a list comprehension?
回答1:
b = [x*2 for x in a if x != 0]
if you put your condition at the end you do not need an else (infact cannot have an else there)
回答2:
Following the pattern:
[ <item_expression>
for <item_variables> in <iterator>
if <filtering_condition>
]
we can solve it like:
>>> lst = [0, 1, 2]
>>> [num
... for num in lst
... if num != 0]
[1, 2]
It is all about forming an if condition testing "nonzero" value.
来源:https://stackoverflow.com/questions/24442091/list-comprehension-with-condition