Suliman Sharif
Suliman Sharif

Reputation: 607

Summing two 2-D lists

so this has kind of stumped me. I feel like it should be an easy problem though. Lets say I have these two lists

a = [[3, 4], [4, 5]]
b = [[1, 2], [4, 6]]

I am trying so it would return the sum of the two 2-D lists of each corresponding element like so

c = [[4, 6], [8, 11]]

I am pretty sure I am getting lost in loops. I am only trying to use nested loops to produce an answer, any suggestions? I'm trying several different things so my code is not exactly complete or set in stone and will probably change by the time someone reponds so I won't leave a code here. I am trying though!

Upvotes: 0

Views: 56

Answers (3)

rnso
rnso

Reputation: 24535

I know it is an old question, but following nested loops code works exactly as desired by OP:

sumlist = []
for i, aa in enumerate(a):
    for j, bb in enumerate(b): 
        if i == j: 
            templist = []
            for k in range(2):
                templist.append(aa[k]+bb[k])
            sumlist.append(templist)
            templist = []
print(sumlist)

Output:

[[4, 6], [8, 11]]

Upvotes: 0

erewok
erewok

Reputation: 7835

You could try some variation on nested for-loops using enumerate (which will give you the appropriate indices for comparison to some other 2d array):

a = [[3, 4], [4, 5]]
b = [[1, 2], [4, 6]]

Edit: I didn't see you wanted to populate a new list, so I put that in there:

>>> c = []
>>> for val, item in enumerate(a):
        newvals = []
        for itemval, insideitem in enumerate(item):
           newvals.append(insideitem + b[val][itemval])
         c.append(newvals)
         newvals = []

Result:

>>> c
[[4, 6], [8, 11]]

Upvotes: 1

idfah
idfah

Reputation: 1438

Use numpy:

import numpy as np

a = [[3, 4], [4, 5]]
b = [[1, 2], [4, 6]]
c = np.array((a,b))
np.sum(c, axis=0)

Upvotes: 0

Related Questions