我是 python 的新手,通过 Python 的简短类(class)和一些谷歌搜索将这些内容组合在一起。我正在尝试比较两个字符串列表,以查看列表 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 No Match in List B
test_2 No Match in List B
test_3 No Match in List B
test_4 No Match in List B
test_5 No Match in List 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)
关于python - 如何检查一个列表中的所有项目是否都在 python 的第二个列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17018148/