gpt4 book ai didi

Python 二维数组求和枚举

转载 作者:太空宇宙 更新时间:2023-11-04 08:44:20 25 4
gpt4 key购买 nike

我正在尝试遍历一个二维数组,获取数组中每个列表的总和。例如我有:

test = [[5, 3, 6], [2, 1, 3], [1, 1, 3], [2, 6, 6], [4, 5, 3], [3, 6, 2], [5, 5, 2], [4, 4, 4], [3, 5, 3], [1, 3, 4]]

我想获取每个较小数组的值,例如 5+3+6 和 2+1+3 并将它们放入一个新数组中。所以我的目标是:

testSum = [14, 6, 5, 14...]. 

我在正确枚举二维数组时遇到问题。好像在跳来跳去。我知道我的代码不正确,但这是我目前所拥有的:

k = 10
m = 3
testSum = []

#create array with 10 arrays of length 3
test = [[numpy.random.randint(1,7) for i in range(m)] for j in range(k)]
sum = 0
#go through each sub-array in test array
for array in test:
#add sums of sub-arrays
for i in array
sum += test[array][i]
testSum.append(sum)

最佳答案

你可以用更pythonic的方式来做,

In [17]: print [sum(i) for i in test]
[14, 6, 5, 14, 12, 11, 12, 12, 11, 8]

In [19]: print map(sum,test)
[14, 6, 5, 14, 12, 11, 12, 12, 11, 8]

关于Python 二维数组求和枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42129788/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com