Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Union of two lists in Python [closed]

Tags:

python

list

I have two lists say:

a = [1, 2, 2, 2, 3]

b = [2, 5, 6]

After doing a union, I should get something like this (don't mind the order):

c = [1, 2, 2, 2, 3, 5, 6]

The final list should contain common elements only once and rest of elements (from both lists) should be copied as they are. Sets can't be used for this as they remove multiple occurrence of an element from the list, which isn't a union. What is a Pythonic way to do so?

like image 649
Rahul Avatar asked Apr 01 '16 06:04

Rahul


People also ask

How do you take the union of two lists in Python?

How to Perform the Union of Lists 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] .

What does union [] mean in Python?

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

Can we use union for list in Python?

We can also make an union of more than two lists. This can be done efficiently by using both the set() and union() function, simultaneously, as shown in the below example.


1 Answers

Perform a union, keeping repetition:

>>> c = a + b
[1, 2, 2, 3, 2, 5, 6]

Perform a union, keeping repetition & order:

>>> c = sorted(a + b)
[1, 2, 2, 2, 3, 5, 6]

Perform an union, no repetition in each list, but repetition allowed in final union, and keeped order:

>>> c = sorted(list(set(a)) + list(set(b)))
[1, 2, 2, 3, 5, 6]

After clarification of the question, the goal is to build a list that take elements (including repetition) of, and then add elements of b if they are not in the new list.

>>> c = a + [e for e in b if e not in a]
[1, 2, 2, 2, 3, 5, 6]

After another clarification of the question, the goal is to build a list containing all elements of input list. But, if elements are in common, they are pushed the same number there

>>> from collections import Counter
>>> def merge(a,b):
...   na, nb = Counter(a), Counter(b)
...   return list(Counter({k: max((na[k], nb[k])) for k in set(a + b)}).elements())
>>> merge([1, 2, 2, 2, 3], [2, 5, 6])
[1, 2, 2, 2, 3, 5, 6]
>>> merge([1, 2, 3], [2, 2, 4])
[1, 2, 2, 4]
like image 165
aluriak Avatar answered Sep 19 '22 12:09

aluriak