我需要检查一个列表是否包含python中另一个列表的每个元素。不完全是设置操作,因为在集合中考虑了不同的值。我该怎么办?
样品: 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。] 我确切知道如何通过哈希映射完成它。但是我想要一些不那么笨重的东西。
答案 0 :(得分:2)
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
答案 1 :(得分:2)
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
答案 2 :(得分:2)
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
答案 3 :(得分:-2)
def包含(a,b): 对于集合(a)中的项目: 如果集合(b)中的项目: 打印'某事或做某事'