【问题标题】:Venn Diagram up to 4 lists - outputting the intersections and unique sets维恩图最多 4 个列表 - 输出交叉点和唯一集
【发布时间】:2011-01-15 16:00:27
【问题描述】:

在我的工作中,我使用了很多维恩图,到目前为止,我一直依赖基于 Web 的“Venny”。这为导出各种交叉点(即仅属于该特定交叉点的元素)提供了很好的选择。此外,它最多可以绘制 4 个列表。

问题是,对大型列表(4K+ 元素)和超过 3 个集合执行此操作是一件苦差事(复制、粘贴、保存...)。因此,我决定专注于自己生成列表并将其用于绘图。

这个冗长的介绍引出了问题的症结所在。给定 3 或 4 个部分包含相同元素的列表,我如何在 Python 中处理它们以获得各种集合(唯一的、4 通用的、仅第一个和第二个通用的等...),如维恩图所示(@ 987654322@, 4 list graphical example)? 3 个列表看起来并不难,但 4 个列表就有点复杂了。

【问题讨论】:

  • 您需要在图形上显示它吗?
  • 使用set生成数据和联合很容易
  • 我不需要图形,因为 Venny 对我来说很容易做到这一点,我想要一些东西来提取列表。

标签: python list venn-diagram


【解决方案1】:

假设你有 python 2.6 或更高版本:

>>> from itertools import combinations
>>>
>>> data = dict(
...   list1 = set(list("alphabet")),
...   list2 = set(list("fiddlesticks")),
...   list3 = set(list("geography")),
...   list4 = set(list("bovinespongiformencephalopathy")),
... )
>>>
>>> variations = {}
>>> for i in range(len(data)):
...   for v in combinations(data.keys(),i+1):
...     vsets = [ data[x] for x in v ]
...     variations[tuple(sorted(v))] = reduce(lambda x,y: x.intersection(y), vsets)
...
>>> for k,v in sorted(variations.items(),key=lambda x: (len(x[0]),x[0])):
...   print "%r\n\t%r" % (k,v)
...
('list1',)
        set(['a', 'b', 'e', 'h', 'l', 'p', 't'])
('list2',)
        set(['c', 'e', 'd', 'f', 'i', 'k', 'l', 's', 't'])
('list3',)
        set(['a', 'e', 'g', 'h', 'o', 'p', 'r', 'y'])
('list4',)
        set(['a', 'c', 'b', 'e', 'g', 'f', 'i', 'h', 'm', 'l', 'o', 'n', 'p', 's', 'r', 't', 'v', 'y'])
('list1', 'list2')
        set(['e', 'l', 't'])
('list1', 'list3')
        set(['a', 'h', 'e', 'p'])
('list1', 'list4')
        set(['a', 'b', 'e', 'h', 'l', 'p', 't'])
('list2', 'list3')
        set(['e'])
('list2', 'list4')
        set(['c', 'e', 'f', 'i', 'l', 's', 't'])
('list3', 'list4')
        set(['a', 'e', 'g', 'h', 'o', 'p', 'r', 'y'])
('list1', 'list2', 'list3')
        set(['e'])
('list1', 'list2', 'list4')
        set(['e', 'l', 't'])
('list1', 'list3', 'list4')
        set(['a', 'h', 'e', 'p'])
('list2', 'list3', 'list4')
        set(['e'])
('list1', 'list2', 'list3', 'list4')
        set(['e'])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-24
    • 2011-12-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多