测试集合是否是子集,考虑集合中每个元素的数量(多重性) [英] Test if set is a subset, considering the number (multiplicity) of each element in the set

查看:28
本文介绍了测试集合是否是子集,考虑集合中每个元素的数量(多重性)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以测试 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
>>> 

这篇关于测试集合是否是子集,考虑集合中每个元素的数量(多重性)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆