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

标签 python set subset multiset multiplicity

我知道我可以测试 set1 是否是 set2 的子集:

{'a','b','c'} <= {'a','b','c','d','e'} # True

但以下也是正确的:

{'a','a','b','c'} <= {'a','b','c','d','e'} # True

我如何让它考虑集合中元素出现的次数,以便:

{'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) 或者避免列表理解的方法。谢谢!

最佳答案

如评论中所述,使用 Counter 的可能解决方案:

from collections import Counter

def issubset(X, Y):
    return len(Counter(X)-Counter(Y)) == 0

关于python - 测试集合是否为子集,考虑集合中每个元素的数量(多重性),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15208369/

相关文章:

python - 如何使用 Pandas/Dask 更快地读取压缩(.gz)文件?

c# - 关于获取和设置的快速问题

r - GoogleVis 和 Shiny

python - 转换为一组自定义集合类在 Python 中返回空集

python - 在 GTK 中将图像缩放到其父按钮大小?

python - 多元高斯的等高线图

c++ - C++设置容器的问题

javascript - 将数组转换为集合以便在 NodeJS 中搜索是否值得

algorithm - **O(n) 时间** 和 **O(n) 空间** 复杂度中的幂集解?

algorithm - 什么软件算法将从一个大集合中选择不同的项目子集