Python 我在说IndexError:列表索引超出范围时出错。我该如何解决这个问题?
变量“answer”用来计算相邻的重复数字。出于某种原因,我得到了一个错误,称为IndexError:list index超出范围。如何解决这个问题?让我们先简化一下代码。状况Python 我在说IndexError:列表索引超出范围时出错。我该如何解决这个问题?,python,list,index-error,Python,List,Index Error,变量“answer”用来计算相邻的重复数字。出于某种原因,我得到了一个错误,称为IndexError:list index超出范围。如何解决这个问题?让我们先简化一下代码。状况 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
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
可以转换为
not i > (len(res) - 1)
i <= (len(res) - 1)
我们使用i+1
索引res
,对于i
的最后一个可能值,该索引将是无效索引(i+1
将等于len(res)
)。我们必须确保不仅i
小于len(res)
,而且i+1
小于len(res)
,这样我们就可以得到这个固定版本的代码:
if res[i]==res[i+1]:
...
而i+1
在您的示例
res
上运行此代码会给出一个4的答案,看起来不错。给它这个方法怎么样
while i + 1 < len(res):
if res[i] == res[i + 1]:
answer += 2
i += 2
else:
i += 1
res=[3,1,1,5,2,4,2,4,3,1,1,5,3]
答案=0
开始=0
启动时
如果您还想计算重叠对,可以使用以下方法:
res = [3, 1, 1, 5, 2, 4, 2, 4, 2, 4, 3, 1, 1, 5, 3]
answer = 0
start = 0
while start < len(res):
if start + 1 < len(res):
if res[start] == res[start + 1]:
answer += 1
start += 2
else:
start += 1
else:
start += 1
print(answer)
另一种办法可以是:
res = [3, 1, 1, 5, 2, 4, 2, 4, 2, 4, 3, 1, 1, 5, 3]
for i, j in zip(res, res[1:]):
if i == j:
amount += 2
枚举(res)中的i的:
如果i
当i==len(res)-1
时会发生什么?满足条件noti>(len(res)-1)
,但如果res[i]==res[i+1]
,则执行。那么什么是i+1
,并且res
应该在该索引处有一个元素吗?试着找出原因:满足while
循环条件的i
的最大值是什么?如果您尝试在if
条件中使用该值,会发生什么情况?特别是res[i+1]
是否有效?无论如何,如果输入数据在一行中有3个或更多相同值,会发生什么情况?这只会计算重复项,但如果输入数据在一行中有3个或更多相同值,则会使用不同的方法。
res = [3, 1, 1, 5, 2, 4, 2, 4, 2, 4, 3, 1, 1, 5, 3]
for i, j in zip(res, res[1:]):
if i == j:
amount += 2
for i, _ in enumerate(res):
if i < len(res) - 1 and res[i] == res[i+1]:
amount += 2