最佳检查列表的元素是否在 python 中的另一个列表中

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 项的列表。我认为一个好的解决方案是创建一个散列 table,但我不知道如何构建它。如果您有什么建议可以留言。

Python sets 基于散列,因此你不能将不可散列的对象放入 sets 中。 而不是计算长度,直接执行 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

I think a good solution can be by creating a hash table, but I don't know exactly how I could build it.

集合已经实施 using hash tables,所以您已经在实施了。

假设您没有(或不关心)重复项,您可以尝试:

list1 = [1,2,3]
list2 = [1,2,3,4]
set(list1).issubset(list2)

请注意如何无需将 list2 转换为集合,请参阅 this answer 上的评论。

编辑:你的解决方案和我的解决方案都是 O(n) 平均,它不会比这更快。但是您的解决方案可以避免一些操作,例如将差异 res 转换为列表以获取其大小。