Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Union of multiple sets in python

[[1, '34', '44'], [1, '40', '30', '41'], [1, '41', '40', '42'], [1, '42', '41', '43'], [1, '43', '42', '44'], [1, '44', '34', '43']] 

I have a list of lists. My aim is to check whether any one sublist has anything in common with other sublists(excluding the first index object to compare). If it has anything in common then unify those sublists.

For example, for this example my final answer should be something like:

[[1, '34, '44', '40' '30', '41', '42', '43']] 

I can understand that I should convert the sublists to sets and then use union() and intersection() operation. But what I am stuck with is to how to compare each set/sublist. I can't run a loop over the list and compare each sublist one by one as the contents of the list would be modified and this would lead to error.

What I want to know is there any efficient method to compare all the sublists(converted to sets) and get union of them?

like image 518
Tapojyoti Mandal Avatar asked Jun 11 '15 07:06

Tapojyoti Mandal


People also ask

How do you find the union of three sets in Python?

In Python, to union two or more sets, you use the union() method: new_set = set.

What does union () do in Python?

The union() method returns a set that contains all items from the original set, and all items from the specified set(s).

How do you list a union in Python?

To perform the union of two lists in python, we just have to create an output list that should contain elements from both the input lists. For instance, if we have list1=[1,2,3,4,5,6] and list2=[2,4,6,8,10,12] , the union of list1 and list2 will be [1,2,3,4,5,6,8,10,12] .


1 Answers

The itertools module makes short work of this problem:

>>> from itertools import chain >>> list(set(chain.from_iterable(d))) [1, '41', '42', '43', '40', '34', '30', '44'] 

Another way to do it is to unpack the list into separate arguments for union():

>>> list(set().union(*d)) [1, '41', '42', '43', '40', '34', '30', '44'] 

The latter way eliminates all duplicates and doesn't require that the inputs first be converted to sets. Also, it doesn't require an import.

like image 76
Raymond Hettinger Avatar answered Oct 14 '22 22:10

Raymond Hettinger