我收到IndexError:列表索引超出范围错误。我不知道为什么。有什么建议吗?
代码正在尝试查看数字列表是否为算术级数,在这种情况下,每个数字都加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]))
答案 0 :(得分:2)
您正在尝试在for循环的第二次迭代中访问num_list
数组的第5个元素。第一次迭代num
变为4之后,因此当程序尝试求值num_list[num + 1]
时,程序将崩溃。
num
变量将实际元素保留在列表中。它不是元素的索引。
要遍历索引,可以尝试使用for num in range(len(num_list) - 1)
来解决该问题。 (在括号中的注-1)
答案 1 :(得分:2)
此:
for num in num_list:
if not (num_list[num + 1] - num_list[num] == delta):
return False
几乎可以肯定不会按照您的想法去做。定义for num in num_list:
时,这意味着num
是列表num_list
中的项。 num
不是索引。因此,如果您的列表为[2, 4, 6, 8, 10]
,则当num
为4
(即列表中的第二项)时,您会超出范围,因为您输入的列表长度仅为5,因此您尝试访问索引num+1
,即5
(索引基于0,所以5
超出范围)
您可能想要这样的东西:
# Start at index 1, or you'll always return false since delta == index1 - index0
for index in range(1, len(num_list)-1):
if not (num_list[num + 1] - num_list[num] == delta):
return False
或更Pythonic(请注意没有索引):
# Again start at index1, zip will handle the edge case of ending nicely so we don't go OB
for num, next_num in zip(num_list[1:], num_list[2:]):
if not (next_num - num == delta):
return False
答案 2 :(得分:1)
您要遍历值,而不是数组的索引。因此,num_list[num]
可能超出范围。由于您引用了i+1
元素,因此最多可以迭代i < n-1
for i, _ in enumerate(num_list[:-1]):
if num_list[i+1] - num_list[i]...
答案 3 :(得分:1)
2件事:
num
是num_list
的元素,而不仅仅是索引。获取索引将是for num in range(len(num_list)):
,您实际上是在调用num_list[num_list[i]]
; num
,您也会调用numlist [num + 1],它已超出数组范围,因为num
已经在最后; 执行for INDEX in range(len(num_list)-1):
和if not (num_list[INDEX + 1] - num_list[INDEX] == delta):
。那应该做。