在这种情况下如何对两个嵌套列表求和 [英] How can sum two nested list in this situation

查看:50
本文介绍了在这种情况下如何对两个嵌套列表求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出列表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]]

如果我只想对列表a(而不是整个列表a)中的列表 [[1.1,-2.1],[-0.6,4.2]] 与列表求和列表b中的[-1.1,4.3] .

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.

例如1.1 +(-1.1),然后是(-2.1)+4.3,依此类推.之后,将存储返回到空列表.我可以使用for循环吗?在这种情况下,最终输出将为[[0,2.2],[-1.7,8.5]]

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

推荐答案

使用:

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

输出:

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

更新:使用for循环:

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

更新:使用列表理解

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

输出:

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

这篇关于在这种情况下如何对两个嵌套列表求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆