概述
for循环时列表长度改变,会发生什么?
以以下两种形式为例:
# 第一种形式
for i in li:
# 第二种形式
for i in range(len(li))
先说结论:
- 无论是哪种遍历,都是严格按照下标进行,li[0]之后必然是li1
- 形式1(for i in li)会不断检查长度确定遍历终点,到达终点停止。
- 形式2(for i in range(len(li)))的长度会在遍历一开始确定,假如数组长度变长,遍历次数不会增多,假如数组长度变短,可能诱发访问越界错误。
import numpy
li = []
for i in range(5):
li.append(10-i)
for i in li:
print(i)
li.pop(0)
print(li)
10
[9, 8, 7, 6]
8
[8, 7, 6]
6
[7, 6]
列表变小,循环次数也变少
li2 = []
for i in range(5):
li2.append(i)
for i in li2:
li2.append(i+5)
if i>20:
break
print(li2)
[0, 1, 2, 3, 4, 5]
[0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6, 7]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]
列表变大,循环次数也变大,(假如没有break,这段代码会无限循环)
li = []
for i in range(5):
li.append(10-i)
for i in range(len(li)):
print(li[i])
li.pop(0)
print(li)
10
[9, 8, 7, 6]
8
[8, 7, 6]
6
[7, 6]
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-4-b4c48012bfa9> in <module>
3 li.append(10-i)
4 for i in range(len(li)):
----> 5 print(li[i])
6 li.pop(0)
7 print(li)
IndexError: list index out of range
列表变小,访问越界错误
li = []
for i in range(5):
li.append(i)
for i in range(len(li)):
print(li[i])
li.append(i+5)
print(li)
0
[0, 1, 2, 3, 4, 5]
1
[0, 1, 2, 3, 4, 5, 6]
2
[0, 1, 2, 3, 4, 5, 6, 7]
3
[0, 1, 2, 3, 4, 5, 6, 7, 8]
4
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
列表变大:循环次数不变
最后
以上就是诚心小天鹅为你收集整理的python: for循环时列表长度改变,会发生什么?的全部内容,希望文章能够帮你解决python: for循环时列表长度改变,会发生什么?所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复