【问题标题】:'continue' the 'for' loop to the previous element'继续''for'循环到前一个元素
【发布时间】:2020-01-05 04:15:26
【问题描述】:

我一直在尝试找到一种方法来将continue 我的for 循环到上一个元素。很难解释。

只有两个清楚,这里是一个例子:

foo = ["a", "b", "c", "d"]

for bar in foo:
    if bar == "c":
        foo[foo.index(bar)] = "abc"
        continue
    print(bar)

执行此操作时,当循环到达'c' 时,它看到bar 等于'c',它将列表中的'c' 替换为continues 到下一个元素& 没有'打印bar。当if 条件为真时,我希望它在替换后循环回'b'。所以它将再次打印'b',就像循环从未到达'c'

背景:我正在做一个项目。如果出现任何错误,我必须从上一个元素继续解决此错误。

这是一个流程图,如果有帮助的话:

我不想修改我现有的列表,除了我所做的替换。我尝试搜索每个不同的关键字,但没有找到类似的结果。

如何继续循环到当前元素的前一个元素?

【问题讨论】:

  • 只使用一个while循环?
  • 使用 while 循环。 python 中的 for 循环与其他语言中的 for 循环非常不同。它实际上就像一个 foreach 循环。
  • 您要打印a、b、b、abc、d吗?
  • @joumaico 没错。但请注意,这不是我的主要目的。这只是一个例子
  • 据我了解,您想打印 a , b ,b , abc, d?第一个 b 是第二个元素,第二个 b 是返回一步后的元素,最后 "abc" 是用 “c” ?

标签: python list loops continue


【解决方案1】:

这里当i对应的值等于c时,该元素会根据你的要求而后退一步,重新打印@ 987654323@abc,最后是 d

foo = ["a", "b", "c", "d"]
i = 0
while i < len(foo):
    if foo[i] == "c":
        foo[i] = "abc"
        i -= 1
        continue
    print(foo[i])
    i += 1

【讨论】:

  • 我从未在我的问题中谈论过while,所有答案都使用while
  • 你不能用 for 因为它帮不了你!
  • 没有。我可以使用for。我回答了我自己的问题。我知道一定有办法。我不会撤销对你的回答的接受,但我希望你看看它。
【解决方案2】:

for 循环中,您不能更改迭代器。请改用while 循环:

foo = ["a", "b", "c", "d"]
i = 0
while i < len(foo):
    if foo[i] == "c":
        foo[foo.index(foo[i])] = "abc"
        i -= 1
        continue
    print(foo[i])
    i += 1    

【讨论】:

  • 如果列表中的第一个元素匹配就会中断!
  • 我推荐这个答案。
  • @SamDaniel 我同意,但它来自对问题的定义,而不是来自答案。
【解决方案3】:

我想使用for,所以我自己创建了代码。我不想修改我的原始列表,所以我复制了我的原始列表

foo = ["a", "b", "c", "d"]
foobar = foo.copy()

for bar in foobar:
    if bar == "c":
        foobar[foobar.index(bar)] = "abc"
        foo[foo.index(bar)] = "abc"
        del foobar[foobar.index("abc")+1:]
        foobar += foo[foo.index("abc")-1:]
        continue
    print(bar)

按预期打印:

a
b
b
abc
d

我原来的名单现在也是:

['a', 'b', 'abc', 'd']

【讨论】:

    【解决方案4】:
    import collections
    left, right = -1,1
    foo = collections.deque(["a", "b", "c", "d"])
    end = foo[-1]
    while foo[0] != end:
        if foo[0] == 'c':
            foo[0] = 'abc'
            foo.rotate(right)
        else:
            print(foo[0])
            foo.rotate(left)
    print(foo[0])
    

    【讨论】:

      猜你喜欢
      • 2021-12-04
      • 1970-01-01
      • 1970-01-01
      • 2018-06-30
      • 1970-01-01
      • 2019-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多