0

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

7
  • What should be the desired result? Commented May 6, 2021 at 19:45
  • not related with your question, why dont you use numpy arrays? Commented May 6, 2021 at 19:45
  • also, see if this can help you stackoverflow.com/questions/13334722/sum-for-list-of-lists Commented May 6, 2021 at 19:47
  • 2
    [[i + j for i, j in zip(x, y)] for x, y in zip(a, b)]? Commented May 6, 2021 at 19:48
  • 1
    "I could just convert them to arrays" - you can convert a list of lists to an array too Commented May 6, 2021 at 19:48

2 Answers 2

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

3 Comments

Why flatten and then reshape? You can just write np.add(a, b) or just a + b to get the desired result.
Yes that can be done after making them numpy arrays but i did not know if he wanted answer in 1d array or 2d, you can add first and then flatten if you don't want to reshape, op's choice
The OP's desired result in the question is [[8,10,12],[5,7,9]], which is the same shape as the original data.
1

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)

Comments

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.