一种很酷的方法是使用显式迭代器
iterator = iter(right)
try:
while True:
r = next(iterator)
if stack.endswith(r):
stack = stack.replace(r, left[right.index(r)])
iterator = iter(right)
except StopIteration:
pass
在这种情况下,这看起来很可怕,因为迭代器没有“has_next”方法,知道何时停止的唯一方法是捕获异常;和 for 循环在这里不起作用,因为它存储了对其迭代器的引用
但在这个非常精确的情况下,真正最惯用的python是使用循环else
子句for
来打破while:
# loop forever
while True:
for r in right:
if stack.endswith(r):
stack = stack.replace(r, left[right.index(r)])
# now break out of the for-loop rerunning while
break
# the else is run when all r in right are consumed
else:
# this break is not in a for loop; it breaks the while
break