繁体   English   中英

最佳检查列表的元素是否在 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 项的列表。 我认为一个好的解决方案是创建一个 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

我认为一个好的解决方案是创建一个 hash 表,但我不知道如何构建它。

集合已经使用 hash 表实现,所以你已经在这样做了。

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

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

请注意如何无需将list2转换为集合,请参阅对此答案的评论。

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

暂无
暂无

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

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