gpt4 book ai didi

python - 我收到错误提示 IndexError : list index out of range. 我该如何解决这个问题?

转载 作者:行者123 更新时间:2023-12-04 00:55:14 24 4
gpt4 key购买 nike

   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。我该如何解决?

最佳答案

让我们从稍微简化代码开始。条件

not i > (len(res) - 1)
可以转换为
i <= (len(res) - 1)
可以进一步转换为
i < len(res)
这意味着 i将始终小于 res 的长度,这使它成为一个有效的索引。然而,体内 while ,在这一行:
if res[i]==res[i+1]:
...
我们索引了 resi + 1 ,这是 i 的最后一个可能值将是无效索引( i + 1 将等于 len(res) )。我们要确保不仅 i小于 len(res) ,还有那个 i + 1小于 len(res) ,给我们这个固定版本的代码:
while i + 1 < len(res):
if res[i] == res[i + 1]:
answer += 2
i += 2
else:
i += 1
在您的示例上运行此代码 res给出 answer共 4 个,看起来不错。

关于python - 我收到错误提示 IndexError : list index out of range. 我该如何解决这个问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62988674/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com