我知道我可以测试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)的方法或避免列表理解的方法。谢谢!
set(A).issubset(B,count=True)
@DSM删除了他的解决方案后,我将借此机会提供一个可以扩展的原型。
>>> class Multi_set(Counter): def __le__(self, rhs): return all(v == rhs[k] for k,v in self.items()) >>> Multi_set(['a','b','c']) <= Multi_set(['a','b','c','d','e']) True >>> Multi_set(['a','a','b','c']) <= Multi_set(['a','b','c','d','e']) False >>> Multi_set(['a','a','b','c']) <= Multi_set(['a','a','b','c','d','e']) True >>>