简体   繁体   English

为什么在这个例子中 pop 方法没有打破 while 循环?

[英]Why doesn't the pop method break the while-loop in this example?

Expected Outcome: while loop will break when z = []预期结果:当 z = [] 时,while 循环将中断

Actual Outcome: Index Error.实际结果:索引错误。 Loop does not break even after pop method "empties" the list.即使在 pop 方法“清空”列表后,循环也不会中断。

Index error at "front_of_list = z[0]" because at that point, z = [] “front_of_list = z[0]”处的索引错误,因为此时 z = []

Example code:示例代码:

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)

If you see properly and print the output:如果您看到正确并打印输出:

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)

This is what you get:这是你得到的:

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

Your while loop doesn't catch that because you pop the element in the if statement but you also pop the element outside it.你的 while 循环没有捕捉到它,因为你在if语句中弹出元素,但你也在它之外弹出元素。

front_of_list = z[0]
print(front_of_list)
popped = z.pop(0)
print(z)

So before the iteration has completed, you pop the element.所以在迭代完成之前,你弹出元素。 Your last element is 7 and you pop that in your if statement.你的最后一个元素是 7,你在 if 语句中弹出它。 Now the list is empty.现在列表是空的。 But you try to pop it again outside the if statement.但是您尝试在if语句之外再次弹出它。 That is the error.这就是错误。

Example of last iteration:上次迭代示例:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM