我有,例如,listy = [[1,-1,2], [3,-2,-4]]
我想进行过滤,以便只获得正元素 [[1,2], [3]]
使用循环和过滤器(lambda x: x > 0, listy)很容易做到这一点,但我想避免循环。
请您参考如下方法:
列表理解可以嵌套:
In [2]: [ [i for i in x if i>0] for x in listy ]
Out[2]: [[1, 2], [3]]
关于filter和list comprehension之间的选择,Guido van Rossum, the BDFL, wrote列表理解更清晰、更快速;
filter(P, S) is almost always written clearer as [x for x in S if P(x)], and this has the huge advantage that the most common usages involve predicates that are comparisons, e.g. x==42, and defining a lambda for that just requires much more effort for the reader (plus the lambda is slower than the list comprehension).
高级主题:处理大型数据集
如果 listy 很大并且您的应用程序允许,您可能希望使用生成器代替列表:
g = ( (i for i in x if i>0) for x in listy )
