我知道如何在单独的行上使用for循环和if语句,例如:

>>> a = [2,3,4,5,6,7,8,9,0]
... xyz = [0,12,4,6,242,7,9]
... for x in xyz:
...     if x in a:
...         print(x)
0,4,6,7,9

我知道我可以使用一个列表理解来组合这些语句时很简单,例如:

print([x for x in xyz if x in a])

但是我在任何地方都找不到一个很好的例子(可以复制和学习)来演示一组复杂的命令(不仅仅是“print x”),这些命令发生在for循环和一些if语句的组合之后。我期待的是这样的:

for x in xyz if x not in a:
    print(x...)

这不是python应该工作的方式吗?


当前回答

你可以像这样使用生成器表达式:

gen = (x for x in xyz if x not in a)

for x in gen:
    print(x)

其他回答

我可能会用:

for x in xyz: 
    if x not in a:
        print(x...)

你可以像这样使用生成器表达式:

gen = (x for x in xyz if x not in a)

for x in gen:
    print(x)
a = [2,3,4,5,6,7,8,9,0]
xyz = [0,12,4,6,242,7,9]  
set(a) & set(xyz)  
set([0, 9, 4, 6, 7])

我个人认为这是最漂亮的版本:

a = [2,3,4,5,6,7,8,9,0]
xyz = [0,12,4,6,242,7,9]
for x in filter(lambda w: w in a, xyz):
  print x

Edit

如果你非常热衷于避免使用lambda,你可以使用部分函数应用程序和使用operator模块(它提供了大多数操作符的函数)。

https://docs.python.org/2/library/operator.html#module-operator

from operator import contains
from functools import partial
print(list(filter(partial(contains, a), xyz)))

我喜欢Alex的回答,因为过滤器正是应用于列表的if,所以如果您想在给定条件下探索列表的子集,这似乎是最自然的方法

mylist = [1,2,3,4,5]
another_list = [2,3,4]

wanted = lambda x:x in another_list

for x in filter(wanted, mylist):
    print(x)

这个方法对于分离关注点很有用,如果条件函数改变了,唯一需要修改的代码就是函数本身

mylist = [1,2,3,4,5]

wanted = lambda x:(x**0.5) > 10**0.3

for x in filter(wanted, mylist):
    print(x)

当您不想要列表中的成员,而是修改这些成员时,生成器方法似乎更好,这似乎更适合生成器

mylist = [1,2,3,4,5]

wanted = lambda x:(x**0.5) > 10**0.3

generator = (x**0.5 for x in mylist if wanted(x))

for x in generator:
    print(x)

此外,过滤器与生成器一起工作,尽管在这种情况下效率不高

mylist = [1,2,3,4,5]

wanted = lambda x:(x**0.5) > 10**0.3

generator = (x**0.9 for x in mylist)

for x in filter(wanted, generator):
    print(x)

当然,这样写还是不错的:

mylist = [1,2,3,4,5]

wanted = lambda x:(x**0.5) > 10**0.3

# for x in filter(wanted, mylist):
for x in mylist if wanted(x):
    print(x)