如何创建一个总和2d数组值的数组

时间:2018-06-13 15:49:27

标签: python python-3.x

[[2, 3, 4, 6, 9],
 [4, 6, 8, 12, 18],
 [6, 9, 12, 18, 27],
 [8, 12, 16, 24, 36],
 [10, 15, 20, 30, 45],
 [12, 18, 24, 36, 54],
 [14, 21, 28, 42, 63],
 [16, 24, 32, 48, 72],
 [18, 27, 36, 54, 81],
 [20, 30, 40, 60, 90]]

我想将值加总为数组。

基本上,我有这个数组数据,如何获得此输出。

输出是这样的

[2+3+4+6+9, 2+3+4+6+18, 2+3+4+6+27, 2+3+4+6+36, 2+3+4+6+45, 2+3+4+6+54, 2+3+4+6+63, 2+3+4+6+71, 2+3+4+6+81, 2+3+4+6+90, 4+3+4+6+9, ...]

我尝试过类似的东西而且没有用

final = [] trans = [*zip(*data)]

k = 0 l = 0

while(k != len(trans) * len(data)):   val = 0   m = 0   for d1 in trans:
    val = val + d1[m * l]
    m = m + 1   l = l + 1   k = k + 1   final.append(val)

2 个答案:

答案 0 :(得分:1)

你想要这个吗?

my_list = [[2, 3, 4, 6, 9],
 [4, 6, 8, 12, 18],
 [6, 9, 12, 18, 27],
 [8, 12, 16, 24, 36],
 [10, 15, 20, 30, 45],
 [12, 18, 24, 36, 54],
 [14, 21, 28, 42, 63],
 [16, 24, 32, 48, 72],
 [18, 27, 36, 54, 81],
 [20, 30, 40, 60, 90]]

sum_list = [sum(i) for i in my_list]
print(sum_list)

答案 1 :(得分:0)

在python2中:

summed_array = map(sum,array)

for python3:

summed_array = list(map(sum,array))

要做你真正要求的事情:

[sum(row[:-1]) + x[-1] for row in array for x in array]