![](/img/trans.png)
[英]How to Check if Python List Contains Elements of Another List Duplicates Not Ignored
[英]Optimal check if the elements of a list are in another list in python
我需要检查一个列表中的项目是否在另一个列表中。 两个列表都包含文件的路径。
list1 = [a/b/c/file1.txt, b/c/d/file2.txt]
list2 = [a/b/c/file1.txt, b/c/d/file2.txt, d/f/g/test4.txt, d/k/test5.txt]
我试过类似的东西:
len1 = len(list1)
len2 = len(list2)
res = list(set(list2) - set(list1))
len3 = len(res)
if len2 - len1 == len3:
print("List2 contains all the items in list1")
但这不是一个最佳选择,我有超过 50k 项的列表。 我认为一个好的解决方案是创建一个 hash 表,但我不知道如何构建它。 如果您有什么建议可以留言。
Python set
是基于散列的,因此您不能将不可散列的对象放入set
中。 而是计算长度,直接执行set difference
:
>>> list1 = ['a/b/c/file1.txt', 'b/c/d/file2.txt']
>>> list2 = ['a/b/c/file1.txt', 'b/c/d/file2.txt', 'd/f/g/test4.txt', 'd/k/test5.txt']
>>> if (set(list1) - set(list2)): # will return empty set (Falsy) if all are contained
print("List2 contains all the items in list1")
List2 contains all the items in list1
这是细分:
>>> difference = set(list1) - set(list2)
>>> difference
set()
>>> bool(difference)
False
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.