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?
1 Answer
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]