如何查看一个列表中的所有项目是否都在python的第二个列表中?

时间:2013-06-10 06:39:29

标签: python list python-2.7 comparison

我是python的新手,并且已经在Python和一些谷歌搜索中使用了一个简短的类。我正在尝试比较两个字符串列表,以查看列表A的所有项目是否在列表B中。如果列表B中没有任何项目,我希望它打印通知消息。

List_A = ["test_1", "test_2", "test_3", "test_4", "test_5"]
List_B = ["test_1", "test_2", "test_3", "test_4"]

代码:

for item in List_A:
     match = any(('[%s]'%item) in b for b in List_B)
     print "%10s %s" % (item, "Exists" if match else "No Match in List B")

输出:

  

test_1列表B中没有匹配

     

test_2列表B中没有匹配

     

test_3列表B中没有匹配

     

test_4列表B中没有匹配

     

test_5列表B中没有匹配

前四个应该匹配但不匹配,第五个是正确的。我不知道它为什么不起作用。有人能告诉我我做错了什么吗?任何帮助将不胜感激。

4 个答案:

答案 0 :(得分:5)

>>> '[%s]'%"test_1"
'[test_1]'

您正在检查“[test_1]”是否是list_B中某个字符串的子字符串,依此类推。

这应该有效:

for item in List_A:
     match = any(item in b for b in List_B)
     print "%10s %s" % (item, "Exists" if match else "No Match in List B")

但是既然你不是在寻找子串,你应该测试in而不是更多:

for item in List_A:
     match = item in List_B
     print "%10s %s" % (item, "Exists" if match else "No Match in List B")

但你可以简单地使用set difference:

print set(List_A) - set(List_B)

答案 1 :(得分:0)

您可以将List_B转换为集合,因为集合提供O(1)查找:

虽然注意集合允许您只存储可散列(不可变)项目。如果List_B包含可变项,则首先将它们转换为不可变项,如果不可行,则排序List_B并使用bisect模块对已排序List_B进行二进制搜索。 / p>

List_A = ["test_1", "test_2", "test_3", "test_4", "test_5"]
List_B = ["test_1", "test_2", "test_3", "test_4"]
s = set(List_B)
for item in List_A:
    match = item in s  # check if item is in set s
    print "%10s %s" % (item, "Exists" if match else "No Match in List B")

<强>输出:

test_1 Exists
test_2 Exists
test_3 Exists
test_4 Exists
test_5 No Match in List B

答案 2 :(得分:0)

只需使用简单的for循环:

List_A = ["test_1", "test_2", "test_3", "test_4", "test_5"]
List_B = ["test_1", "test_2", "test_3", "test_4"]
for i in List_A:
    print "{:>10} {}".format(i, "Exists" if i in List_B else "No Match in List B")

答案 3 :(得分:0)

List_A = ["test_1", "test_2", "test_3", "test_4", "test_5"]
List_B = ["test_1", "test_2", "test_3", "test_4"]

for item in List_A:
     match = any((str(item)) in b for b in List_B)
     print "%10s %s" % (item, "Exists" if match else "No Match in List B")

将输出

test_1 Exists
test_2 Exists
test_3 Exists
test_4 Exists
test_5 No Match in List B