在for循环中移回迭代

时间:2013-01-17 07:34:27

标签: python for-loop

所以我想做这样的事情:

for i in range(5):
    print(i);
    if(condition==true):
        i=i-1;

然而,无论出于何种原因,即使我正在减少i,循环似乎也没有注意到。有没有办法重复迭代?

8 个答案:

答案 0 :(得分:25)

Python中的

for循环总是向前发展。如果您希望能够向后移动,则必须使用其他机制,例如while

i = 0
while i < 5:
    print(i)
    if condition:
        i=i-1
    i += 1

甚至更好:

i = 0
while i < 5:
    print(i)
    if condition:
        do_something()
        # don't increment here, so we stay on the same value for i
    else:
        # only increment in the case where we're not "moving backwards"
        i += 1

答案 1 :(得分:6)

使用range的Python循环是按照设计与C / C ++ / Java for - 循环不同的。对于每次迭代,i都设置为range(5)的下一个值,无论你对i做什么。

您可以使用while循环:

i = 0
while i<5:
    print i
    if condition:
        continue
    i+=1

但老实说:我会退后一步,再想一想你原来的问题。可能你会找到一个更好的解决方案,因为这样的循环总是容易出错。 Python for - 循环设计为不同的原因是有原因的。

答案 2 :(得分:3)

你对Python中的循环有误解。 for循环不关心你在每次迭代时对i做什么,因为它根本不与循环逻辑相关。修改i只是重新绑定局部变量。

您需要使用while循环来实现您期望的行为,i的状态确实会影响循环的控制流:

import random

i = 0
while i < 5:
    print(i)
    i += 1
    if random.choice([True, False]):
        i -= 1

答案 3 :(得分:2)

利用while循环:

i = 0
while i < 5:
    print(i)
    if condition:
        i -= 1
    i += 1

正如已经提到的,这是相当单一的Python。也许如果你发布你想要实现的目标,我们可以提供一些更好的建议。

答案 4 :(得分:2)

range(5)会在其中创建一个包含04的数字的列表 - [0, 1, 2, 3, 4]

当你对它运行for循环时,你正在迭代列表。执行i-= 1只会减少列表中特定元素的,迭代将继续。

与此处提出的其他答案一样,您应该使用while循环。

i= 0
while i<5:
    # do stuff
    if #condition:
        i-= 1 # or +
    i+= 1

答案 5 :(得分:2)

重复许多其他答案,为了完整起见,您需要使用while loop

i = 0
while i < 5:
    print(i)
    if (not condition):
       i+=1

如果你想在循环中移回迭代(而不是重复迭代),那么使用它:

i = 0
while i < 5:
    print(i)
    if (condition):
        i -= 1
    else:
        i += 1

基本上,while i < 5会对每次迭代进行求值,并检查i < 5是否为i。因此,通过递减/不改变i,我们得到这样的结果:( 1->2->3-(condition satisfied)> 3 -> 4 -> 5的值)

不更改:1->2->3-(condition satisfied)>2 -> 3 -> 4 -> 5

减少:i=i-1

你的for循环中for没有让它重复迭代的原因很简单。在i循环中,i被赋予for循环中下一个项的值。 Python可以不关心你使用for i in <your_iterable>:<do whatever>做什么,只要它能够为它分配下一个项目。因此,for循环_i = 0 _length = len(<your_iterable>) while _i < _length: i = _i _i += 1 <do whatever> 更接近于此:

_

但是,在此类比中,您将无法访问_i谓词变量(_lengthfor loop)。这就是我简化i逻辑的方法。请注意,无论分配给_i的是什么,都会在下一次迭代时将其分配给i,并且循环实际上并不关心{{1}}是什么。

答案 6 :(得分:1)

在Python中,可以在迭代器(in循环中的for..in之后的内容)与其使用者(循环内的代码)之间建立双向交换。为此,您可以在使用者代码中使用send来“注入”生成器中的值。在您的情况下,您可以在条件满足后简单地发回当前值,并将range调用包装在生成器中,该生成器重复发送回它的任何内容。这里有一些代码供你玩,故意为了清晰起见:

def repeateble(it):
    buf, it = None, iter(it)
    while True:
        if buf is None:
            # the buffer is empty, send them the next elem
            val = next(it)
        else:
            # there's something in the buffer
            # let's send that back
            val = buf

        # send the value and wait what they say
        back = yield val

        if back:
            # they've sent us something!
            # give them some dummy value as a result of send()
            yield None 
            # and save what they've sent in a buffer
            # for the next iteration
            buf = back

        else:
            # they haven't sent anything
            # empty the buffer
            buf = None


from random import randint

# create a repeateble generator
rng = repeateble(range(100))

for x in rng:
    print(x)

    # check "some condition"...
    if randint(1, 100) > 80:
        print('repeat:')
        # send the current value back to the generator
        # it will be returned on the next iteration
        rng.send(x)

答案 7 :(得分:-2)

如果要遍历文件并根据条件提取前几行,则可以使用readlines。


with open("myfile.txt", "r") as f:
    text = f.readlines()
    for row in range(0, len(text)):
        if re.search("Error", text[row]):
            print(text[row-1].strip())