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
>>>
这篇关于测试集合是否是子集,考虑集合中每个元素的数量(多重性)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:测试集合是否是子集,考虑集合中每个元素的数量(多重性)
基础教程推荐
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
