在Python 3中遍历数组 [英] Iterating over arrays in Python 3
问题描述
我已经有一段时间没有编码了,并试图重新使用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中遍历数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!