6

我一直在使用 matplotlib-venn 生成 3 组的维恩图。如下图所示。

我想问如何找到这些集合相交的值。例如,与集合 A 和集合 B 相交的 384 个值是什么?与集合 A、集合 B 和集合 C 相交的 144 个值是什么?非常值得。

谢谢你。

罗德里戈

Matplotlib-venn 图

4

2 回答 2

6

我知道这是一个老问题,但我最近研究了一个类似的问题。为了将来的访问者,我在这里分享我的解决方案。下面的代码提供了一个解决方案来识别维恩图每个部分的成员资格。仅交集是不够的,您还必须减去不需要的集合。

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
于 2017-02-10T14:36:52.357 回答
4

假设您使用的是内置 Pythonset对象,获取两个集合之间的交集非常简单。看这个例子:

>>> a = set(range(30))
>>> b = set(range(25,50))
>>> a.intersection(b)
set([25, 26, 27, 28, 29])
于 2015-06-29T18:52:11.753 回答