我知道如何在单独的行上使用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应该工作的方式吗?
使用intersection或intersection_update
十字路口:
A = [2,3,4,5,6,7,8,9,0]
Xyz = [0,12,4,6,242,7,9]
Ans = sorted(set(a).intersection(set(xyz)))
intersection_update:
A = [2,3,4,5,6,7,8,9,0]
Xyz = [0,12,4,6,242,7,9]
B = set(a)
b.intersection_update(某某)
b是答案
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 (x for x in xyz if x not in a):
print(x)
12
242
注意,生成器是内联的。这是在python2.7和python3.6上测试的(注意print;))
即便如此,它还是很麻烦:x被提到了四次。
我喜欢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)