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

标签 python list python-2.7 comparison

我是 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/

相关文章:

python - 导入错误 : cannot import name wsgiserver

Python:寻找最长路径

python - 如何按照 python 中 matplotlib 中收到的顺序对条形进行排序?

python - 使用 jinja2 在 python web 应用程序中加载 css

python - 在 Python 中将两个多维列表合并为一个列表

python - 将单列 .csv 文件转换为列表变量

python - 从元组的嵌套列表中删除元组

php - Python 脚本不会从 PHP 调用中执行

Python Dict inside List inside Dict - 可以理解吗?

python - 按唯一组的数量对 Pandas 列进行排序