问题描述
我已经有一段时间没有编写代码并尝试重新使用 Python.我正在尝试编写一个简单的程序,通过将每个数组元素值添加到总和来对数组求和.这就是我所拥有的:
I haven't been coding for awhile and trying to get back into Python. I'm trying to write a simple program that sums an array by adding each array element value to a sum. This is what I have:
def sumAnArray(ar):
theSum = 0
for i in ar:
theSum = theSum + ar[i]
print(theSum)
return theSum
我收到以下错误:
line 13, theSum = theSum + ar[i]
IndexError: list index out of range
我发现我想要做的事情显然就是这么简单:
I found that what I'm trying to do is apparently as simple as this:
sum(ar)
但显然我无论如何都没有正确地遍历数组,而且我认为这是我需要为其他目的正确学习的东西.谢谢!
But clearly I'm not iterating through the array properly anyway, and I figure it's something I will need to learn properly for other purposes. Thanks!
推荐答案
当你像你一样在数组中循环时,你的 for 变量(在这个例子中是 i
)是你数组的当前元素.
When you loop in an array like you did, your for variable(in this example i
) is current element of your array.
例如如果你的ar
是[1,5,10]
,则每次迭代中的i
值为1
、5
和 10
.因为你的数组长度是 3,所以你可以使用的最大索引是 2.所以当 i = 5
你得到 IndexError
.你应该把你的代码改成这样:
For example if your ar
is [1,5,10]
, the i
value in each iteration is 1
, 5
, and 10
.And because your array length is 3, the maximum index you can use is 2. so when i = 5
you get IndexError
.You should change your code into something like this:
for i in ar:
theSum = theSum + i
或者如果你想使用索引,你应该创建一个范围从 0 ro array length - 1
.
Or if you want to use indexes, you should create a range from 0 ro array length - 1
.
for i in range(len(ar)):
theSum = theSum + ar[i]
这篇关于在 Python 3 中迭代数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!