for r in right:
if stack.endswith(r):
stack=stack.replace(r,left[right.index(r)])
当if
部分获得true
时,我希望r
指向right
的起始索引。
当r
获得3rd element of right
并更新if
时,假设true
指向stack
,则for
循环从{{1}继续}}。我想在3rd element of right
更新时从for
开始first element of right
循环。
怎么做?
答案 0 :(得分:4)
一种很酷的方法是使用显式迭代器
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
答案 1 :(得分:0)
也许将它嵌套在while循环中?
keepLooping = True
while keepLooping:
doBreak = False
for r in right:
if stack.endswith(r):
stack=stack.replace(r,left[right.index(r)])
doBreak = True
break
if doBreak:
break
keepLooping = False
因此,当完全搜索权限而没有stack.endswith(r)评估为True时,进程将终止。
答案 2 :(得分:-1)
这里的主要任务是确定真实的回报和错误的回报。为什么不做样品:
While len(right) > 0:
removedIdx = None
for r in right:
if stack.endswith(r):
removedIdx = right.index[r]
stack.stack.replace(r, left[removedIdx])
break
if removed is not None:
right.pop(removedIdx)
else:
break