一个列表包含另一个重复的列表

2024-03-28 09:29:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要检查一个列表是否包含python中另一个列表的所有元素。不完全是set操作,因为在set中考虑了不同的值。我该怎么做?你知道吗

样品: a是较大的列表,b是较小的集合

a = [1, 1, 2, 4], b = [1, 2, 3] -> False
a = [1, 1, 2, 3], b = [1, 2, 3] -> True
a = [1, 2, 4], b = [1, 2, 1] -> False // Because b has two 1s but a has only one.

我想请你仔细看看第三个案子。你知道吗

[N.B.]我确切地知道如何通过哈希映射来实现。但我想要不那么笨重的。你知道吗


Tags: falsetrue元素only列表样品onebut
3条回答

Counter的简单单行程序

def isin(a, b): return not (Counter(b) - Counter(a))

演示:

>>> isin([1, 1, 2, 4], [1, 2, 3])
False
>>> isin([1, 1, 2, 3], [1, 2, 3])
True
>>> isin([1, 1, 2, 4], [1, 2, 1])
True
>>> isin([1, 2, 4], [1, 2, 1])
False
from collections import Counter

def is_contained(a,b):
    aCount = Counter(a)
    bCount = Counter(b)
    return all(aCount[x] >= bCount[x] for x in bCount)



>>> is_contained([1, 1, 2, 4],[1, 2, 3])
False
>>> is_contained([1, 1, 2, 3], [1, 2, 3])
True
>>> is_contained([1, 2, 4],  [1, 2, 1])
False
from collections import Counter

def is_contained(a, b):
    aCount = Counter(a)
    bCount = Counter(b)
    # think of it as aCount >= bCount in set-operations
    return aCount & bCount == bCount

相关问题 更多 >