我正在尝试使用 a 对列表的值求和for
环形。这是我的代码:
def sumAnArray(ar):
theSum = 0
for i in ar:
theSum = theSum + ar[i]
return theSum
我收到以下错误:
line 13, theSum = theSum + ar[i]
IndexError: list index out of range
我发现我想做的事情显然很简单sum(ar)
。但我想明白:为什么我会得到这个IndexError
,以及我应该如何写for
循环代替?循环实际上是如何工作的?
For a technical overview of how Python implements for
loops and the iterator protocol, see e.g. How does a Python for loop with iterable work? https://stackoverflow.com/questions/1292189.
当循环列表时,for
变量(在本例中i
) 代表列表的当前元素.
例如,给定ar = [1, 5, 10]
, i
将有连续的值1
, 5
and 10
每次通过循环。由于列表的长度为3,最大允许索引 https://stackoverflow.com/questions/1098643是 2。因此,第二次循环时,i == 5
, an IndexError
被提出。
代码应该是这样的:
for i in ar:
theSum = theSum + i
为了能够对列表进行索引,请使用range
而不是直接迭代列表:
for i in range(len(ar)):
theSum = theSum + ar[i]
这边走,i
自然 https://stackoverflow.com/questions/11364533接受所有有效的索引值ar
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)