【发布时间】:2015-03-13 05:04:38
【问题描述】:
我不太确定是否可能有另一个重复,但根据主题提出问题。
这个问题的目的不是要弄清楚你是否应该使用for循环来实现哨兵控制。
而是看看它是否可以做到,从而更好地理解for和while循环之间的区别。
【问题讨论】:
标签: python
我不太确定是否可能有另一个重复,但根据主题提出问题。
这个问题的目的不是要弄清楚你是否应该使用for循环来实现哨兵控制。
而是看看它是否可以做到,从而更好地理解for和while循环之间的区别。
【问题讨论】:
标签: python
使用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...
(灵感来自堆栈溢出问题“Looping from 1 to infinity in Python”。)
【讨论】:
在不导入任何模块的情况下,您还可以使用for 进行“哨兵”控制循环,方法是将循环设置为无穷大,break 使用condition:
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')
虽然这会创建一个非常大的无限列表,会消耗内存。
【讨论】: