所以,我有一个看起来像这样的列表
[[[1, 2], [3, 4], [5, 6]],
[[7, 8], [9, 10], [11, 12]],
[[13, 14], [15, 16], [17, 18]],
[[19, 20], [21, 22], [23, 24]]]
我希望它看起来像这样
[[3, 7, 11],
[15, 19, 23],
[27, 31, 35],
[39, 43, 27]]
即3 = sum([1, 2]), 7 = sum([3, 4]), ...
。
我已经尝试过嵌套循环,但是没有找到任何能达到预期结果的东西,有人知道我该怎么做吗?
答案 0 :(得分:2)
这将很好地完成这项工作,而且imo比列表理解更具可读性。
lists = [[[1, 2], [3, 4], [5, 6]],
[[7, 8], [9, 10], [11, 12]],
[[13, 14], [15, 16], [17, 18]],
[[19, 20], [21, 22], [23, 24]]]
new_lists = []
for nested in lists:
new_ls = []
for ls in nested:
new_ls.append(sum(ls))
new_lists.append(new_ls)
>>> new_lists
[[3, 7, 11], [15, 19, 23], [27, 31, 35], [39, 43, 47]]
答案 1 :(得分:1)
您还可以使用列表推导:
[[sum(x) for x in triple] for triple in lists]
在上面的列表理解中,三元组将是您的三个双倍的列表,因此第一个for循环将覆盖这些。然后x将是三元组内的每个双组列表,因此我们对其进行求和,同时使用以下方括号将其保留在原始三元组内:
[sum(x) for x in triple]
输出:
[[3, 7, 11], [15, 19, 23], [27, 31, 35], [39, 43, 47]]
答案 2 :(得分:0)
如果您乐于使用第三方库,则可以使用NumPy并沿一个维度求和:
import numpy as np
A = np.array([[[1, 2], [3, 4], [5, 6]],
[[7, 8], [9, 10], [11, 12]],
[[13, 14], [15, 16], [17, 18]],
[[19, 20], [21, 22], [23, 24]]])
res = A.sum(2)
结果:
array([[ 3, 7, 11],
[15, 19, 23],
[27, 31, 35],
[39, 43, 47]])
另请参阅:What are the advantages of NumPy over regular Python lists?