Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
359 views
in Technique[技术] by (71.8m points)

python - How can sum two nested list in this situation

Given list a, b

a=[[[1.1,-2.1],
    [-0.6,4.2]],
   [[3.9,1.3],
    [-1.3,1.2]]]

b=[[-1.1,4.3],
   [-1.4,2.4]]

If I just want to sum the list [[1.1,-2.1],[-0.6,4.2]] in the list a (not the whole list a) with the list [-1.1,4.3] in list b.

For instance 1.1+(-1.1) then (-2.1)+4.3 and so on. After that store back to an empty list. Can I do this with for loop? In this case, the final output will be[[0, 2.2],[-1.7, 8.5]]

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use:

import numpy as np
c = (np.array(a[0]) + b[0]).tolist()

Output:

>>> c
[[0.0, 2.1999999999999997], [-1.7000000000000002, 8.5]]

Update Using for loop:

 c = []
 for row in a[0]: 
     c.append([])
     for x, y in zip(row, b[0]):
         c[-1].append(x+y)

Update: Using list comprehension

c = [[x + y for x,y in zip(row, b[0])] for row in a[0]]

Output:

>>> c
[[0.0, 2.1999999999999997], [-1.7000000000000002, 8.5]]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...