列表理解与条件 [英] List comprehension with condition
本文介绍了列表理解与条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个简单的清单。
>>> 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]
但理想的结果是。
>>> b
[2, 4]
我可以这样做
>>> a = [0, 1, 2]
>>> def f(arg):
... for x in arg:
... if x != 0:
... yield x*2
...
>>> list(f(a))
[2, 4]
或使用'过滤器'和一个lambda
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?
推荐答案
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)
这篇关于列表理解与条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文