3

I have two lists in python:

L1=[[100, 1], [101, 2]]
L2=[[100, 3], [101, 4], [102, 5]]

and I want to merge them so I get:

L_merge=[[100, 4], [101, 6], [102, 5]]

It is important that the two lists might be not of the same size.

I was trying to use dictionaries but could not figure it out. I am happy to use numpy, pandas or any other tools to get that merger.

Marcus Müller
  • 34,677
  • 4
  • 53
  • 94
valenzio
  • 773
  • 2
  • 9
  • 21
  • Adapting the solution from the link above: `collections.Counter(dict(L1)) + collections.Counter(dict(L2))`. There's probably a way to skip converting lists to `dict`s first. See http://stackoverflow.com/q/11290092/2301450 – vaultah Oct 20 '16 at 10:02
  • What do you know about the two lists? Are they both definitely sorted? Could there be "gaps" in the middle where an item is in one list but not in the other? Are you sure that each item is a list of two integers? And so on. – Rory Daulton Oct 20 '16 at 10:05
  • the "duplicate" question is about combining dicts, not lists – mkj Oct 20 '16 at 10:27
  • @ Rory Daulton So sorting should not be a problem since you could do that before hand. Gaps in the middle is definitly a possilbe case. Yes each item in the list has two integers, but it would be interesting if you have more than 2, however all the lists that are merged will have the same amount of items. – valenzio Oct 20 '16 at 11:03

3 Answers3

5

You could use a collections.Counter on both lists and simply sum them:

from collections import Counter

L1 = [[100, 1], [101, 2]]
L2 = [[100, 3], [101, 4], [102, 5]]

L_merge = (Counter(dict(L1)) + Counter(dict(L2))).items()
print(list(L_merge))
# [(100, 4), (101, 6), (102, 5)]
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
  • This works great, just a quick follow up: why does `list(L_merge)` produces tupples instead of lists anyway to avoid it (just out of curiosity). – valenzio Oct 20 '16 at 11:20
  • @valenzio The `items` method of a dictionary produces a list of tuples. You can use a list comprehension to cast the tuples into lists. – Moses Koledoye Oct 20 '16 at 12:22
0

why not just use a for loop:

L_merge = L2
for i in len(L1):
    L_merge[i][-1] += L1[i][-1]

The one caveat is that this only works if L2 is the longer of the 2 lists

Jack Cooper
  • 408
  • 1
  • 4
  • 10
  • Yes that works, I guess you could check in advance which of the lists is longer, but it seems rather cumbersome – valenzio Oct 20 '16 at 10:59
0
L1=[[100, 1], [101, 2]]
L2=[[100, 3], [101, 4], [102, 5]]

d = {}
for a,b in L1+L2:
  d[a] = d.get(a,0) + b
L_merge = [[k,v] for k,v in d.items()]

print(L_merge)
mkj
  • 2,761
  • 5
  • 24
  • 28