我正在学习在线 Python 类(class),但不明白我的列表范围如何与排序程序一起运行。
这段代码有效,但我不明白为什么负数 1 是必需的
for i in range(len(myList)-1):
我尝试通过删除有效的代码来破坏代码。显然,如果没有“-1”,第 6 行就超出了范围。所以我知道为了让代码运行这是必要的,但我不明白为什么取长度并显然从中减去 1 会扩大范围。
myList = [8, 10, 6, 2, 4] # list to sort
swapped = True # it's a little fake - we need it to enter the while loop
while swapped:
swapped = False # no swaps so far
for i in range(len(myList) - 1):
if myList[i] > myList[i + 1]:
swapped = True # swap occured!
myList[i], myList[i + 1] = myList[i + 1], myList[i]
print(myList)
最佳答案
Len(mylist) 等于 5。但是,myList[5] 会抛出错误,因为它超出了范围。因为您在倒数第二行中向“i”添加 1,所以会出现错误。大多数编程语言从 0 开始计数,直到小于列表长度的 1。
关于python - 为什么列表的长度必须包含 -1 才能在 for 循环中容纳 +1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56794307/