如何在Python中对嵌套列表求和?

qij5mzcb  于 2023-01-08  发布在  Python
关注(0)|答案(3)|浏览(157)

我想在Python中对一个嵌套列表求和,下面是一个例子:

[[[1,2], [3,4]], [[5,6], [7,8]]] -> [[6,8], [10,12]]

基本上,它应该对两个N行N列的嵌套列表求和,并输出一个N行N列的列表。
到目前为止,我所尝试做的是将所有嵌套的列表元素连接到第一个列表中:

for idx in range(len(implemented_moves[0])):
    for snd_idx in range(1, len(implemented_moves)):
        implemented_moves[0][idx] +=  implemented_moves[snd_idx][idx]

输出[它合并而不是concat]:第一个月

wwtsj6pe

wwtsj6pe1#

如果您具有同类维度,则这对于numpy是一个很好的工作:

import numpy as np

l = [[[1,2], [3,4]], [[5,6], [7,8]]]
out = np.array(l).sum(0).tolist()

对于纯Python,使用zip

l = [[[1,2], [3,4]], [[5,6], [7,8]]]
out = [[c+d for c, d in zip(a, b)] for a, b in zip(*l)]
# or
# out = [[sum(y) for y in zip(*x)]for x in zip(*l)]

输出:

[[6, 8], [10, 12]]
7xzttuei

7xzttuei2#

内置zip + sum功能:

lst = [[[1,2], [3,4]], [[5,6], [7,8]]]
summed_rows = [list(map(sum, zip(*gr))) for gr in zip(*lst)]
print(summed_rows)
[[6, 8], [10, 12]]
9rygscc1

9rygscc13#

下面是一个简单的例子:

# input
arrays = [
    [
        [1,2,3],
        [4,5,6],
        [7,8,9]
    ],
    [
        [1,2,3],
        [4,5,6],
        [7,8,9]
    ]
]

# split into 2 separate arrays
arr1, arr2 = arrays

# don't assume these are square matrices
n, m = len(arr1), len(arr1[0])

# calculate the output
output = [[arr1[row][col] + arr2[row][col] for col in range(m)] for row in range(n)]

# print formatted output
print('\n'.join(' '.join(f'{x:2}' for x in row) for row in output))

#  2  4  6
#  8 10 12
# 14 16 18

相关问题