【发布时间】:2013-02-18 22:38:10
【问题描述】:
我知道我可以测试 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) 或避免列表推导的方法。谢谢!
【问题讨论】:
-
{'a','a','b','c'}与{'a','b','c'}完全相同。这就是集合的意义。 -
在 Python 中,set 不能有重复项。你可能不想使用collection.Counter,它可以被认为是一个多重集合
-
您是在寻找多组吗?然后使用
collections.Counter()。 -
计数器不这样做,因为
Counter('aabc') <= Counter('aaabcd')给出了 True,但Counter('abce') <= Counter('aabcd')也是如此。第二个字符串中显然没有'e'。
标签: python set subset multiset multiplicity