Reputation: 13
So I want to add the 3rd value of the elements in a list of lists if the first and second values are equal. And if not, I want the non-equal ones to be added to my sum list.
first=[[1,1,5],[2,3,7],[3,5,2],[4,4,6]]
second=[[1,1,3],[4,2,4],[2,3,2]]
sum=[]
for i in ((first)):
for j in ((second)):
if i[0]==j[0] and i[1]==j[1]:
sum.append([i[0],j[1],i[2]+j[2]])
print(sum)
so this gives me [[1, 1, 8], [2, 3, 9]]
but I want [3,5,2],[4,4,6],[4,2,4]
in my sum
list too. How do I do this in python?
Upvotes: 0
Views: 109
Reputation: 736
I tried to do it without dictionaries or libraries:
first = [[1,1,5],[2,3,7],[3,5,2],[4,4,6]]
second = [[1,1,3],[4,2,4],[2,3,2]]
checked = []
sum = []
for n_i, i in enumerate(first):
for n_j, j in enumerate(second):
if i[0]==j[0] and i[1]==j[1]:
sum.append([i[0],j[1],i[2]+j[2]])
checked.append([n_i,n_j]) # Save the used index
# Delete used index
[first.pop(i[0]) and second.pop(i[1]) for i in reversed(checked)]
# Append non-used index
[sum.append(first.pop(0)) for x in range(0,len(first))]
[sum.append(second.pop(0)) for x in range(0,len(second))]
print(sum)
Returns:
[[1, 1, 8], [2, 3, 9], [3, 5, 2], [4, 4, 6], [4, 2, 4]]
Upvotes: 0
Reputation: 164623
One solution is to use collections.defaultdict
from the standard library.
The idea is to set your dictionary keys as a tuple of your first 2 elements and increment by the third. Then aggregate keys and values via a dictionary comprehension.
first = [[1,1,5],[2,3,7],[3,5,2],[4,4,6]]
second = [[1,1,3],[4,2,4],[2,3,2]]
from collections import defaultdict
from itertools import chain
d = defaultdict(int)
for i, j, k in chain(first, second):
d[(i, j)] += k
res = [[*k, v] for k, v in d.items()]
print(res)
[[1, 1, 8], [2, 3, 9], [3, 5, 2], [4, 4, 6], [4, 2, 4]]
Here is the equivalent solution without using any libraries, utilising dict.setdefault
:
d = {}
for i, j, k in first+second:
d.setdefault((i, j), 0)
d[(i, j)] += k
res = [[*k, v] for k, v in d.items()]
Upvotes: 1