Reputation: 823
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.
Upvotes: 3
Views: 516
Reputation: 2811
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)
Upvotes: 0
Reputation: 78536
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)]
Upvotes: 5
Reputation: 418
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
Upvotes: 0