繁体   English   中英

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

[英]How do I check to see if all of the items in one list are in a second list in python?

我是python的新手,并且在Python和一些Googling上的一小节课中将它们组合在一起。 我正在尝试比较两个字符串列表,以查看列表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中没有匹配项

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

>>> '[%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")

但是您可以简单地使用集合差异:

print set(List_A) - set(List_B)

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

不过请注意,集合仅允许您存储可哈希(不可变)的项目。 如果List_B包含可变项,则首先将它们转换为不可变项;如果不可能,则对List_B排序并使用bisect模块对排序后的List_B进行二进制搜索。

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

只需使用一个简单的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")
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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM