【发布时间】:2020-11-09 07:24:05
【问题描述】:
res = [3, 1, 1, 5, 2, 4, 2, 4, 2, 4, 3, 1, 1, 5, 3]
while not i>(len(res)-1):
if res[i]==res[i+1]:
answer+=2
i+=2
else:
i+=1
变量“answer”应该计算彼此相邻的重复数字。出于某种原因,我收到错误消息 IndexError: list index out of range。我该如何解决这个问题?
【问题讨论】:
-
i == len(res) - 1时会发生什么?满足条件not i > (len(res) - 1),然后执行if res[i] == res[i+1]。那么i + 1是什么,res是否应该在该索引处有一个元素? -
尝试推理:满足
while循环条件的i的最大值是多少?如果您尝试在if条件中使用该值会发生什么 - 特别是,res[i+1]是否有效? -
无论如何,如果输入数据连续有3个或更多相同的值会发生什么?
标签: python list index-error