Home > Software engineering >  Element-wise sum of lists within lists of lists in Python
Element-wise sum of lists within lists of lists in Python

Time:01-13

I'm working on Python and I want to make an element-wise sum of each list within 3 lists of lists. I'll try to simplify the problem to explain better.

Input:

a = [['alpha','beta','gamma'],['delta','epsilon','zeta'],['eta','theta','iota']]
b = [['AB'],['CD'],['EF']]
c = [['1','2','3'],['4','5','6'],['7','8','9']]

The outcome I need is:

d = [['alpha','beta','gamma','AB','1','2','3'],['delta','epsilon','zeta','CD','4','5','6'],['eta','theta','iota','EF','7','8','9']]

What I tried is:

d = []
for x in a:
    y = [a[x]   b[x]   c[x]]
    d.append(y)

However I get the error "TypeError: list indices must be integers or slices, not list" because x is defined as a list equal to ['alpha','beta','gamma']

CodePudding user response:

Yes, you can 'add up' the sub lists to form new lists in d:

a = [[1,2,3], [4,5,6], [7,8,9]]
b = [[11,12,13], [14,15,16], [17,18,19]]
c = [[21,22,23], [24,25,26], [27,28,29]]

d = []
for a_i,b_i,c_i in zip(a,b,c):
    d.append(a_i   b_i   c_i)

print(d)

Output as requested.

In fact, you can use the built-in sum():

d = []
for items in zip(a, b, c):
    d.append(sum(items, start=[]))

print(d)

CodePudding user response:

Try numpy:

import numpy as np
    
a = [[1,2,3],[4,5,6],[7,8,9]]
b = [[11,12,13],[14,15,16],[17,18,19]]
c = [[21,22,23],[24,25,26],[27,28,29]]

a = np.array(a)
b = np.array(b)
c = np.array(c)
    
d = np.concatenate([a, b, c], axis=1)
    
print(d)
#[[ 1  2  3 11 12 13 21 22 23]
#[ 4  5  6 14 15 16 24 25 26]
#[ 7  8  9 17 18 19 27 28 29]]
  • Related