Reputation: 79
Let's say I have two lists of lists, a and b:
a = [[1,2,3],[4,5,6]]
b = [[7,8,9],[1,2,3]]
If a and b were both lists of numbers, I could just convert them to arrays and obtain the sum a+b using Python. However, it seems I am unable to do the same if a and b are lists of lists. Is there a similar method, without using for or while cicles?
Edit The desired result would be [[8,10,12],[5,7,9]]
Upvotes: 0
Views: 75
Reputation: 131
List compression:
[[a + b for a, b in zip(x, y)]for x, y in zip(a, b)]
Another way:
k = []
for x, y in zip(a, b):
p = []
for a, b in zip(x, y):
p.append(a + b)
k.append(p)
print(k)
Upvotes: 1
Reputation: 95
import numpy as np
a = [[1,2,3],[4,5,6]]
b = [[7,8,9],[1,2,3]]
a=np.array(a)
a=a.flatten()
b=np.array(b)
b=b.flatten()
c=np.add(a,b)
print(a)
print(b)
print(c)
output:
a=[1 2 3 4 5 6]
b=[7 8 9 1 2 3]
c=[ 8 10 12 5 7 9]
after this if you want list of list you can reshape it like:
c=np.reshape(c,[2,3])
Upvotes: 1