Venn Diagram up to 4 lists - output intersections and unique sets

I use a lot of Venn diagrams in my work, and so far I have relied on the Venny web. This provides a good option for exporting various intersections (i.e., Elements that belong only to that particular intersection). In addition, it has charts of up to 4 lists.

The problem is that doing this with large lists (4K + items) and more than three sets is the complexity (copying, pasting, saving ...). So I decided to focus on creating lists and use it only for building.

This long introduction leads to the point. Given 3 or 4 lists that partially contain the same elements, how can I process them in Python to get different sets (unique, common for 4, common only for the first and second, etc.), As shown in the Venn diagram ( 3 graphic example of a list , 4 lists of graphic examples )? It does not look too complicated for 3 lists, but for 4 it becomes somewhat complicated.

+4
source share
1 answer

Assuming you have python 2.6 or better:

>>> 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']) 
+6
source

Source: https://habr.com/ru/post/1300975/


All Articles