【发布时间】:2018-09-28 17:30:53
【问题描述】:
我收到 IndexError: list index out of range 错误。我不确定为什么。有什么建议吗?
代码试图查看数字列表是否是算术级数,在这种情况下,每个数字都加 2。
def is_arith_progession(num_list):
delta = num_list[1] - num_list[0]
for num in num_list:
if not (num_list[num + 1] - num_list[num] == delta):
return False
else:
return True
print(is_arith_progession([2, 4, 6, 8, 10]))
【问题讨论】:
-
您永远不会在代码中的任何地方施加
2的限制。delta是否总是定义为列表中前两个元素之间的值差? -
for num in num_list:遍历列表的 值。然后,您使用 value+1 对其进行索引:num_list[num + 1]- 没有多大意义....如果你给它一个[3,2,1]的列表,第一个已经不在bounds(这个列表只有从 0 到 2 的索引。
标签: python python-3.x indexing error-handling