q-c*_*ute 12 python arrays sum python-3.x
我没有编写一段时间并尝试重新使用Python.我正在尝试编写一个简单的程序,通过将每个数组元素值添加到一个总和来对数组求和.这就是我所拥有的:
def sumAnArray(ar):
theSum = 0
for i in ar:
theSum = theSum + ar[i]
print(theSum)
return theSum
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
line 13, theSum = theSum + ar[i]
IndexError: list index out of range
Run Code Online (Sandbox Code Playgroud)
我发现我正在尝试做的事情显然就像这样简单:
sum(ar)
Run Code Online (Sandbox Code Playgroud)
但显然我并没有正确地遍历数组,我认为这是我需要为其他目的正确学习的东西.谢谢!
Mr *_*iny 19
当您像在数组中那样循环时,for变量(在此示例中i)是数组的当前元素。
例如,如果你的ar就是[1,5,10],将i在每次迭代中值是1,5和10。并且由于数组长度为3,因此可以使用的最大索引为2。因此,当i = 5您获得时IndexError。您应该将代码更改为如下所示:
for i in ar:
theSum = theSum + i
Run Code Online (Sandbox Code Playgroud)
或者,如果要使用索引,则应从0 ro创建一个范围array length - 1。
for i in range(len(ar)):
theSum = theSum + ar[i]
Run Code Online (Sandbox Code Playgroud)