Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.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
为什么需要-1来索引python列表中的错误索引超出循环的范围_Python_Python 3.x_For Loop - Fatal编程技术网

为什么需要-1来索引python列表中的错误索引超出循环的范围

为什么需要-1来索引python列表中的错误索引超出循环的范围,python,python-3.x,for-loop,Python,Python 3.x,For Loop,如果我们使用len(lst)-1 为什么?len(lst)是4,因此您的范围将超过0、1、2和3。当i为3时,lst[i+1]将为lst[4]。4不是lst的有效索引 但是,如果您执行范围(len(lst)-1),您将只运行0、1和2。因此,当i为2时,您将比较数组的最后两个元素,即lst[2]和lst[3]这是因为python列表从0索引到n-1,其中n是列表中存在的元素数 范围(len(lst))将从0循环到len(lst)-1。但是您也在循环中使用lst[i+1],这会使数组在上一次迭代中

如果我们使用
len(lst)-1
为什么?

len(lst)
是4,因此您的
范围将超过0、1、2和3。当
i
为3时,
lst[i+1]
将为
lst[4]
。4不是
lst
的有效索引


但是,如果您执行
范围(len(lst)-1)
,您将只运行0、1和2。因此,当
i
为2时,您将比较数组的最后两个元素,即
lst[2]
lst[3]
这是因为python列表从
0
索引到
n-1
,其中
n
是列表中存在的元素数

  • 范围(len(lst))
    将从0循环到
    len(lst)-1
    。但是您也在循环中使用
    lst[i+1]
    ,这会使数组在上一次迭代中访问超出范围的索引,从而导致错误。例如,如果您的列表长度为4,那么在最后一次迭代中,
    i
    将为3,并且您正在访问
    lst[i+1]
    ,这是
    lst[4]
    ,它超出了列表的范围

  • 当您使用
    range(len(lst)-1)
    时,您只是从0迭代到
    len(lst)-1
    ,这意味着即使在最后一次迭代中,您也只能访问到
    lst[len(lst)-1]
    ,这是最后一次的最后一个索引,并且永远不会访问越界索引。因此,在您的案例中,这是迭代循环的正确方法


  • 假设这是您的列表:

    lst = [1,2,3,4]
    for i in range(len(lst)):
        if lst[i] == lst[i+1]:
             print(True)
    
    现在,当您这样做时:

    [1, 2, 3, 4]
    
    该范围将为您提供
    i
    的值,如下所示:

    for i in range(len(lst))
    
    在此语句中,当
    i
    3
    时,您还尝试访问不存在的索引
    4

    0, 1, 2, 3
    

    因此,例外。

    请以更容易理解的方式重写您的问题。你不能以“错误”开头发帖,请在发帖前给出上下文等。提前谢谢。
    0, 1, 2, 3
    
    if lst[i] == lst[i+1]: