首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Python matplotlib-venn查找相交值

使用Python matplotlib-venn查找相交值
EN

Stack Overflow用户
提问于 2015-06-29 18:48:59
回答 2查看 4.6K关注 0票数 6

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

我想问,如何才能找到这些集合相交的值。例如,与A和B相交的384个值是什么?相交集A、集B和集C的144个值是多少?而且很有价值。

谢谢。

罗德里戈

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-06-29 18:52:11

假设您使用的是内置Python set对象,那么获得两个集合之间的交集非常简单。参见此示例:

代码语言:javascript
复制
>>> a = set(range(30))
>>> b = set(range(25,50))
>>> a.intersection(b)
set([25, 26, 27, 28, 29])
票数 4
EN

Stack Overflow用户

发布于 2017-02-10 14:36:52

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

代码语言:javascript
复制
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
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31123268

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档