[英]List comprehension with condition
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. 'if'在列表推导中需要'else',所以我想出了这个。
>>> 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 或使用'过滤器'和lambda
>>> a = [0, 1, 2]
>>> list(filter(lambda x: x != 0, a))
[1, 2]
How do I get this result using a list comprehension? 如何使用列表推导获得此结果?
b = [x*2 for x in a if x != 0]
如果你把条件放在最后你不需要别的(事实上不能有其他的)
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. 这是关于形成if条件测试“非零”值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.