我不太确定是否可能还有另一个重复项,但根据主题提出问题。
这个问题的目的不是找出是否应该使用for
循环来实现哨兵控制。
而是看看是否可以做到,从而更好地了解for
和while
循环之间的区别。
使用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')
尽管这会创建一个非常大的无限列表,从而消耗内存。