-3
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循环从 继续3rd element of right。我想从更新时开始for循环。first element of rightstack

怎么做?

4

3 回答 3

5

一种很酷的方法是使用显式迭代器

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
于 2013-07-31T23:54:11.930 回答
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 时,该过程将终止。

于 2013-07-31T23:42:17.160 回答
-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
于 2013-08-01T00:08:15.283 回答