Merging a List with Duplicates

I need to combine two lists in Python3, where duplicates can exist, and for one set of them, the resulting list will contain as the maximum number 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?

+6
source share
3 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 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.

+12
source

Why use lists first? This data is similar to me:

 [1,2,2,5] -> {1: 1, 2: 2, 5: 1} [2,5,5,5,9] -> {2: 1, 5: 3, 9: 1} 

Then it is simple:

 keys = set(a.keys()+b.keys()) vals = [max(a.get(n, 0), b.get(n, 0)) for n in keys] d = dict(zip(keys, vals)) print d 

Result:

{1: 1, 2: 2, 5: 3, 9: 1}

+2
source
  • Convert arrays to dictionaries with a[key] = count

  • Create a new dictionary with the rules c[key] = a.get(key, 0) > b.get(key, 0) and a[key] or b[key] . You need to iterate through both the keys in a and b bs.

  • Expand Dictionary, result += [value] * key

+1
source

Source: https://habr.com/ru/post/897384/


All Articles