我知道我可以测试 set1 是否是 set2 的子集:
{'a','b','c'} <= {'a','b','c','d','e'} # True
但以下也是正确的:
{'a','a','b','c'} <= {'a','b','c','d','e'} # True
我如何让它考虑集合中元素出现的次数,以便:
{'a','b','c'} <= {'a','b','c','d','e'} # True
{'a','a','b','c'} <= {'a','b','c','d','e'} # False since 'a' is in set1 twice but set2 only once
{'a','a','b','c'} <= {'a','a','b','c','d','e'} # True because both sets have two 'a' elements
我知道我可以这样做:
A, B, C = ['a','a','b','c'], ['a','b','c','d','e'], ['a','a','b','c','d','e']
all([A.count(i) == B.count(i) for i in A]) # False
all([A.count(i) == C.count(i) for i in A]) # True
但我想知道是否有更简洁的东西,比如 set(A).issubset(B,count=True)
或者避免列表理解的方法。谢谢!
最佳答案
如评论中所述,使用 Counter
的可能解决方案:
from collections import Counter
def issubset(X, Y):
return len(Counter(X)-Counter(Y)) == 0
关于python - 测试集合是否为子集,考虑集合中每个元素的数量(多重性),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15208369/