这个while循环如何工作?

时间:2016-11-22 14:57:23

标签: python while-loop deque

希望有人可以解释这个循环中发生了什么。

x=deque([(1,2,3)])
while x:
    a,b,c = x.popleft()
    do stuff with values in x
    x.append((d,e,f))

我认为x是一个deque,其中包含3个不断被新值替换的项目。但是我从来没有遇到过没有某种条件的while循环。循环如何知道何时停止?

3 个答案:

答案 0 :(得分:0)

x=deque([(1,2,3)]) # create new deque
while x: # while not empty
    a,b,c = x.popleft() # pop values and assign them to a and b and c
    # do stuff with values in x - this is comment too
    x.append((d,e,f)) # assumes produced new values d 
                      #and e and f and pushes them to x
# this assumes there is always d and e and f values and stays forever in loop 

如此处Python 2.7: How to check if a deque is empty?

所述

答案 1 :(得分:0)

正如所写,该代码是一个无限循环,因为它以与删除数据相同的速率添加数据。

如果要减小大小,则while x将在双端队列为空时终止循环。

答案 2 :(得分:-1)

x=deque([(1,2,3)])的布尔值为True,因为它有一个值且不等于None。这是一个像while 1:while True:这样的infite循环。

要使此循环结束,您必须在满足条件时使用break或设置x = None以打破循环