如何在python中条件变为true后重置for循环中列表的指针?

时间:2013-07-31 23:25:04

标签: python

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循环。

怎么做?

3 个答案:

答案 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