我需要验证一个列表是否是另一个列表的子集-布尔返回是我所寻求的。

在交叉路口后的小列表上测试相等性是最快的方法吗?考虑到需要比较的数据集的数量,性能是极其重要的。

在讨论的基础上补充进一步的事实:

对于许多测试,这两个列表是否都是相同的?其中一个是静态查找表。 需要是一个列表吗?它不是——静态查找表可以是任何性能最好的表。动态的是一个字典,我们从中提取键来执行静态查找。

在这种情况下,最佳解决方案是什么?


当前回答

下面是我如何知道如果一个列表是另一个列表的子集,在我的情况下,序列对我很重要。

def is_subset(list_long,list_short):
    short_length = len(list_short)
    subset_list = []
    for i in range(len(list_long)-short_length+1):
        subset_list.append(list_long[i:i+short_length])
    if list_short in subset_list:
        return True
    else: return False

其他回答

由于没有人考虑比较两个字符串,下面是我的建议。

当然,您可能想检查管道(“|”)是否不属于这两个列表,可能会自动选择另一个char,但您已经明白了。

使用空字符串作为分隔符不是一个解决方案,因为数字可以有几个数字([12,3]!= [1,23])

def issublist(l1,l2):
    return '|'.join([str(i) for i in l1]) in '|'.join([str(i) for i in l2])
>>> a = [1, 3, 5]
>>> b = [1, 3, 5, 8]
>>> c = [3, 5, 9]
>>> set(a) <= set(b)
True
>>> set(c) <= set(b)
False

>>> a = ['yes', 'no', 'hmm']
>>> b = ['yes', 'no', 'hmm', 'well']
>>> c = ['sorry', 'no', 'hmm']
>>> 
>>> set(a) <= set(b)
True
>>> set(c) <= set(b)
False

假设项是可哈希的

>>> from collections import Counter
>>> not Counter([1, 2]) - Counter([1])
False
>>> not Counter([1, 2]) - Counter([1, 2])
True
>>> not Counter([1, 2, 2]) - Counter([1, 2])
False

如果你不关心重复的项目。[1,2, 2]和[1,2],然后使用:

>>> set([1, 2, 2]).issubset([1, 2])
True

在交叉路口后的小列表上测试相等性是最快的方法吗?

. is子集将是最快的方法。在测试子集之前检查长度不会提高速度,因为你仍然有O(N + M)个条目要遍历和检查。

大多数解决方案都认为列表没有副本。如果你的列表确实有重复,你可以试试这个:

def isSubList(subList,mlist):
    uniqueElements=set(subList)
    for e in uniqueElements:
        if subList.count(e) > mlist.count(e):
            return False     
    # It is sublist
    return True

它确保子列表的元素永远不会与list不同,或者公共元素的数量更多。

lst=[1,2,2,3,4]
sl1=[2,2,3]
sl2=[2,2,2]
sl3=[2,5]

print(isSubList(sl1,lst)) # True
print(isSubList(sl2,lst)) # False
print(isSubList(sl3,lst)) # False

另一种解决方案是使用十字路口。

one = [1, 2, 3]
two = [9, 8, 5, 3, 2, 1]

set(one).intersection(set(two)) == set(one)

集合的交点包含集合1

(OR)

one = [1, 2, 3]
two = [9, 8, 5, 3, 2, 1]

set(one) & (set(two)) == set(one)