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 several times). Operator |
gives you a union of multisets where each element appears max (apperances_in_counter1, appearances_in_counter2) times.
This class was added in Python 2.7 and 3.1.
source share