考虑集合中每个元素的数量(多重性),测试集合是否为子集 [英] Test if set is a subset, considering the number (multiplicity) of each element in the set
本文介绍了考虑集合中每个元素的数量(多重性),测试集合是否为子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道我可以使用以下命令测试set1是否是set2的子集:
I know I can test if set1 is a subset of set2 with:
{'a','b','c'} <= {'a','b','c','d','e'} # True
但以下内容也是正确的:
But the following is also True:
{'a','a','b','c'} <= {'a','b','c','d','e'} # True
我如何考虑集合中某个元素出现的次数,以便:
How do I have it consider the number of times an element in the set occurs so that:
{'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
我知道我可以做类似的事情:
I know I could do something like:
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)
,或者是一种摆脱列表理解的方法.谢谢!
But I was wondering if there was something more succinct like set(A).issubset(B,count=True)
or a way to stay from list comprehensions. Thanks!
推荐答案
@DSM删除了他的解决方案后,我将借此机会提供一个可以扩展的原型
As @DSM deleted his solution , I will take the opportunity to provide a prototype based on which you can expand
>>> 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
>>>
这篇关于考虑集合中每个元素的数量(多重性),测试集合是否为子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文