0

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?

2 Answers 2

1

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()]
Sign up to request clarification or add additional context in comments.

4 Comments

Since this is Python 3, you could do [*k, v]. But maybe that's not appropriate at this level.
Well, this works perfectly well! But I don't want to use any libraries since we haven't seen those in my class yet. But thanks anyways!
chain.from_iterable((first, second)) can just be chain(first, second) or first + second.
@AlexHall, Thanks for your suggestions, I have updated. Using chain here to avoid building a new list.
0

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]]

1 Comment

This is what I was looking for in the first place, because it is easier to do any mathematical operation like subtraction just by changing i[2]+j[2] with i[2]-j[2]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.