我一直在使用matplotlib-venn生成3组的维恩图。如下所示。
我想问一下如何找到这些集合的相交值。例如,与集合A和集合B相交的384个值是多少?与集合A,集合B和集合C相交的144个值是什么?非常值得。
谢谢。
罗德里戈
答案 0 :(得分:2)
假设您正在使用内置的Python set
对象,获取两个集合之间的交集非常简单。见这个例子:
>>> a = set(range(30))
>>> b = set(range(25,50))
>>> a.intersection(b)
set([25, 26, 27, 28, 29])
答案 1 :(得分:0)
我知道这是一个老问题,但我最近也遇到了类似的问题。为了未来的访问者,我在这里分享我的解决方案。下面的代码提供了一个解决方案,用于识别维恩图的每个部分的成员资格。仅交叉点是不够的,您还必须减去不需要的集合。
def get_venn_sections(sets):
"""
Given a list of sets, return a new list of sets with all the possible
mutually exclusive overlapping combinations of those sets. Another way
to think of this is the mutually exclusive sections of a venn diagram
of the sets. If the original list has N sets, the returned list will
have (2**N)-1 sets.
Parameters
----------
sets : list of set
Returns
-------
combinations : list of tuple
tag : str
Binary string representing which sets are included / excluded in
the combination.
set : set
The set formed by the overlapping input sets.
"""
num_combinations = 2 ** len(sets)
bit_flags = [2 ** n for n in range(len(sets))]
flags_zip_sets = [z for z in zip(bit_flags, sets)]
combo_sets = []
for bits in range(num_combinations - 1, 0, -1):
include_sets = [s for flag, s in flags_zip_sets if bits & flag]
exclude_sets = [s for flag, s in flags_zip_sets if not bits & flag]
combo = set.intersection(*include_sets)
combo = set.difference(combo, *exclude_sets)
tag = ''.join([str(int((bits & flag) > 0)) for flag in bit_flags])
combo_sets.append((tag, combo))
return combo_sets