Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 我在说IndexError:列表索引超出范围时出错。我该如何解决这个问题?_Python_List_Index Error - Fatal编程技术网

Python 我在说IndexError:列表索引超出范围时出错。我该如何解决这个问题?

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

变量“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
        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