简体   繁体   中英

How to add elements in a 2D array in Python

To be honest, i don't really know how to properly explain what i want, so i better show it. Basically what i want to do is add elements from 2 different 2D lists

a = [[5, 4, 5, 4], [4, 5, 6, 8]]

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

And i wan't to merge them in a 2D array named c, so it should look something like this:

c = [[6, 6, 9, 9], [9, 11, 12, 10]]

I looked around, but sum and zip functions didn't give me the desired output. Thanks in advance for any help

A simple list comprehension and zip will be sufficient, Use:

c = [[x + y for x, y in zip(s1, s2)] for s1, s2 in zip(a, b)]

Result:

#print(c)
[[6, 6, 9, 9], [9, 11, 12, 10]]

In fact I could do this by using two zip functions, one inside another.

c = []
for x, y in zip(a, b):
  array = []
  for e1, e2 in zip(x, y):
    array.append(e1+e2)
  c.append(array)
print(c)

The output would be:

[[6, 6, 9, 9], [9, 11, 12, 10]]

What you are seeking is essentially matrix addition:

import numpy as np
a = np.array([[5, 4, 5, 4], [4, 5, 6, 8]])
b = np.array([[1, 2, 4, 5], [5, 6, 6, 2]])
c = a + b

Where "array" is numpy's vector and matrix object, so when you return "c", you should see

>>> c
array ([[6, 6, 9, 9],
       [9, 11, 12, 10]])

Since you need the result in a new array, I'm creating a new matrix C as a copy of A. So that i can easily add B to A. You can do this:

c = a
for i in range(0,len(a)):
    for j in range(0,len(a[0]):
        c[i][j] = a[i][j] + b[i][j] 
print(c)

You can use for loop to merge 2 arrays.

c = [[a[i][j] + b[i][j] for j in range(len(a[0]))] for i in range(len(a))]

You can use a nested loop to solve the problem.

a = [[5, 4, 5, 4], [4, 5, 6, 8]]
b = [[1, 2, 4, 5], [5, 6, 6, 2]]
c=[]

l=len(a)
for i in range(l):
    temp=[]
    l2=len(a[i])
    for j in range(l2):
        p=a[i][j]+b[i][j]
        temp.append(p)
    c.append(temp)

print(c)

You can use a loop for this.

from builtins import len

def insaneSum(x,y):

newTable = x #creates a copie of your first array
i = 0
j = 0
while i < len(x):
    while j < len(x[i]):

        newTable[i][j] = x[i][j] + y[i][j] #replaces value of copie for the sum

        j = j+1
    i = i+1

return newTable

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

c = insaneSum(a,b) print(c)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM