2016-11-22 54 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'。 –