while循环如何工作?

问题描述 投票:2回答:3

希望某人可以解释while循环的情况。

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

我知道x是具有3个项目的deque,这些项目不断被新值替换。但是我从来没有遇到没有某种条件的while循环。循环如何知道何时停止?

python while-loop deque
3个回答
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?中所述


0
投票

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

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


-1
投票

x=deque([(1,2,3)])的布尔值是True,因为它具有一个值并且不等于None。这是一个无限循环,例如while 1:while True:

为了使循环结束,您必须在满足条件时使用break或将x = None设置为中断循环

© www.soinside.com 2019 - 2024. All rights reserved.