[英]Why doesn't the pop method break the while-loop in this example?
预期结果:当 z = [] 时,while 循环将中断
实际结果:索引错误。 即使在 pop 方法“清空”列表后,循环也不会中断。
“front_of_list = z[0]”处的索引错误,因为此时 z = []
示例代码:
z = [6,3,7,4,9,7,8,4,5,7]
while z:
front_of_list = z[0]
if z[0] == 7:
print("SEVEN!")
popped = z.pop(0)
front_of_list = z[0]
print(front_of_list)
popped = z.pop(0)
如果您看到正确并打印输出:
z = [6,3,7,4,9,7,8,4,5,7]
while z:
front_of_list = z[0]
if z[0] == 7:
print("SEVEN!")
popped = z.pop(0)
front_of_list = z[0]
print(front_of_list)
popped = z.pop(0)
print(z)
这是你得到的:
6
[3, 7, 4, 9, 7, 8, 4, 5, 7]
3
[7, 4, 9, 7, 8, 4, 5, 7]
SEVEN!
4
[9, 7, 8, 4, 5, 7]
9
[7, 8, 4, 5, 7]
SEVEN!
8
[4, 5, 7]
4
[5, 7]
5
[7]
SEVEN!
Traceback (most recent call last):
File "/.../your file", line 7, in <module>
front_of_list = z[0]
IndexError: list index out of range
你的 while 循环没有捕捉到它,因为你在if
语句中弹出元素,但你也在它之外弹出元素。
front_of_list = z[0]
print(front_of_list)
popped = z.pop(0)
print(z)
所以在迭代完成之前,你弹出元素。 你的最后一个元素是 7,你在 if 语句中弹出它。 现在列表是空的。 但是您尝试在if
语句之外再次弹出它。 这就是错误。
上次迭代示例:
while z:
front_of_list = z[0] #=== last element is 7
if z[0] == 7:
print("SEVEN!") #=== Yes
popped = z.pop(0) #=== 7 is removed from the list. So list is []
front_of_list = z[0] #=== No element is in the list so you cannot index it. Hence an IndexError
print(front_of_list)
popped = z.pop(0)
print(z)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.