簡體   English   中英

您可以使用for循環在Python中實現哨兵控制的循環嗎?

[英]Can you use a for loop to implement a sentinel controlled loop in Python?

我不太確定是否還會有其他重復項,但請按照主題進行提問。

這個問題的目的不是找出是否應該使用for循環來實現哨兵控制。

而是看它是否可以完成,從而更好地理解forwhile循環之間的區別。

使用itertools可以:

>>> import itertools
>>>
>>> SENTINEL = 0
>>> for i in itertools.count():
....:    if SENTINEL >= 10:
....:        print "Sentinel value encountered! Breaking..."
....:        break
....:    
....:    SENTINEL = SENTINEL + 1
....:    print "Incrementing the sentinel value..."
....: 
Incrementing the sentinel value...
Incrementing the sentinel value...
Incrementing the sentinel value...
Incrementing the sentinel value...
Incrementing the sentinel value...
Incrementing the sentinel value...
Incrementing the sentinel value...
Incrementing the sentinel value...
Incrementing the sentinel value...
Incrementing the sentinel value...
Sentinel value encountered! Breaking...

(受堆棧溢出問題“ 在Python中從1循環到無窮大 ”的啟發。)

在不導入任何模塊的情況下,您還可以通過循環到無窮大並按condition break來進行for的“前哨”控制循環:

infinity = [0]
sentinelValue = 1000
for i in infinity:
    if i == sentinelValue:
        break

    # like a dog chasing the tail, we move the tail...
    infinity.append(i+1)

    print('Looped', i, 'times')

print('Sentinel value reached')

盡管這會創建一個非常大的無窮大列表,但該列表會占用內存。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM