如果列表中的多个项目在其他列表中--Python

时间:2013-12-13 14:14:04

标签: python

我想查看一个列表中的多个项目是否在另一个列表中。
所以这部分程序基本上是:

list1 = [a, b, c, d]
list2 = [c, d, e, f]
if 2(list1) in list2
#Do Stuff

但是这会返回错误: “TypeError:'int'对象不可调用”

6 个答案:

答案 0 :(得分:6)

您可以使用sets intersection查找两个列表中的常用元素数量:

if len(set(list1) & set(list2)) >= 2:

答案 1 :(得分:2)

你想要做的是一些简单的集算术:

if len(set(list1) & set(list2)) == 2:
    # code to execute conditionally

这会将每个列表转换为集合,这些集合与列表类似,但使用与数学集相同的约束。有关详细信息,请查看Python docs on sets

答案 2 :(得分:2)

如果将列表转换为集合,则可以使用setintersection找到两者中的元素

list1 = ['a', 'b', 'c', 'd']
list2 = ['b', 'd', 'e', 'f']

common = set(list1) & set(list2)

然后,您可以测试结果列表的长度来完成您的工作

if(common):
    #do stuff

答案 3 :(得分:2)

我猜你试图检查第一个列表中的2个项目的子集是否包含在第二个列表中。这可以这样做:

list1 = ['a', 'b', 'c', 'd']
list2 = ['c', 'd', 'e', 'f']
if len(set(list1).intersection(set(list2))) == 2:
    #Do something

答案 4 :(得分:1)

您收到错误是因为您尝试将2作为函数调用。它只是在句法上或语义上都是正确的。

要查看一个列表中的多个项目是否在另一个列表中,请执行以下操作:

count = 0
for item in list1:
    if item in list2:
        count += 1

if count == 2:
    # do stuff

for循环遍历列表一并计算list1中list1中有多少项。然后,完成后,您可以检查计数器的所需值。

答案 5 :(得分:1)

如果您想查看两个列表中存在哪些项目,则使用集合更容易:

print set(list1).intersection(set(list2))