2016-11-22 60 views
1

希望有人可以解释这个while循环是怎么回事。这个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是不断被新值替换一个deque有3项。但是我从未遇到没有某种条件的while循环。循环如何知道何时停止?

+4

一切都在Python有它布尔值。 “deques”也是。它们在空时返回“False”。这就是你的退出条件。说了这么多,就有这样的循环(至少是这样):'while True:'。这些循环只能使用'break'从内部终止! –

+1

另请注意,您的deque并不是三个,而只是一个元素(是三个元组),并且该循环可能永远不会停止,因为'x'在结尾处永远不会是空的,除非'x.append'(除非在省略的代码中有'break'或者'continue') –

回答

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

'do something with x in value'可能是'd','e'和'f'的来源。所以它不完全是一个评论,而是一个伪代码。这是我的错误,至少 –

+0

@ Ev.Kounis是的,但可能 – obayhan

-1

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

这个循环结束,你要么必须使用break当条件满足或设置x = None打破循环

+2

“x = deque([(1,2,3)]的布尔值是True,因为它有一个值,不等于None”。这不完全正确。如果deque为空,则deque的布尔值(与其他序列类型一样)也是False。因此,“while x”不是无限循环的同义词,实际上对于序列类型而言很常见。然而,当条件被检查时,deque实际上永远不会是空的,在循环结尾处使用'append'。 –