Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

list union with duplicates

Tags:

python

I need to unite two lists in Python3,where duplicates can exist,and for one set of these the resulting list will contain as many as max in both lists.An example might clarify it:

[1,2,2,5]( some operator)[2,5,5,5,9]=[1,2,2,5,5,5,9]

Ideas?

like image 946
kaiseroskilo Avatar asked Sep 15 '11 12:09

kaiseroskilo


1 Answers

You can use the collections.Counter class:

>>> from collections import Counter
>>> combined = Counter([1,2,2,5]) | Counter([2,5,5,5,9])
>>> list(combined.elements())
[1, 2, 2, 5, 5, 5, 9]

It functions as a multiset (an unordered collection where each element can appear multiple times). The | operator gives you the union of the multisets, where each element appears max(apperances_in_counter1, appearances_in_counter2) times.

This class was added in Python 2.7 and 3.1.

like image 84
interjay Avatar answered Nov 01 '22 20:11

interjay