测试集合是否是子集,考虑集合中每个元素的数量(多重性)

2022-01-17 00:00:00 python set subset multiset multiplicity

问题描述

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

相关文章