Python 这到底是怎么超出范围的?

Python 这到底是怎么超出范围的?,python,python-2.7,for-loop,runtime-error,Python,Python 2.7,For Loop,Runtime Error,我试着运行这个小循环。我得到一个错误: for i in range(len(lst)): if lst[i] > lst[i+1]: lst[i],lst[i+1] = lst[i+1],lst[i] 错误: Traceback (most recent call last): File "C:/Python27/bubblesort.py", line 10, in <module> IndexError: list index out of

我试着运行这个小循环。我得到一个错误:

for i in range(len(lst)):
    if lst[i] > lst[i+1]:
        lst[i],lst[i+1] = lst[i+1],lst[i]
错误:

Traceback (most recent call last):
  File "C:/Python27/bubblesort.py", line 10, in <module>
IndexError: list index out of range

我想不起来了,我错过了什么?有人帮忙。

当你的列表有最后一个索引i时,你可以再次增加它。i的范围一直到lenlst-1,它是lst中的最后一个索引。但您在上一个索引之外再添加1个:

>>> lst = ['foo', 'bar', 'baz']
>>> len(lst)
3
>>> lst[2]  # length - 1 is the last element
'baz'
>>> lst[3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

Python列表索引从0开始,而不是从1开始。比如说,

list = ['a','b','c']
for element in list:
    print element,
    print list.index(element)
输出

a 0
b 1
c 2

print len(list)
3
输出

a 0
b 1
c 2

print len(list)
3

假设您访问序列中的最后一个索引,然后尝试访问i+1,为什么您会对它超出范围感到惊讶?尝试使用lenlst-1而不是lenlstFWIW,您可以使用扩展切片表示法交换列表项:lst[i:i+2]=lst[i+1:i-1:-1]。