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
但以下也是正确的:
{'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
我知道我可以这样做:
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
>>>
这篇关于测试集合是否是子集,考虑集合中每个元素的数量(多重性)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:测试集合是否是子集,考虑集合中每个元素的数量(多重性)


- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01