Python - 重新启动 for 循环的方法,类似于“继续” for while 循环?

发布于 2024-09-18 14:43:23 字数 388 浏览 14 评论 0原文

基本上,我需要一种方法将控制权返回到 for 循环的开头,并且在满足特定条件时采取操作后实际上重新启动整个迭代过程。

我想做的是这样的:

    for index, item in enumerate(list2):
    if item == '||' and list2[index-1] == '||':
        del list2[index]
        *<some action that resarts the whole process>*

这样,如果 ['berry','||','||','||','pancake] 在列表中,我最终会得到:

[ '浆果','||','煎饼'] 代替。

谢谢!

Basically, I need a way to return control to the beginning of a for loop and actually restart the entire iteration process after taking an action if a certain condition is met.

What I'm trying to do is this:

    for index, item in enumerate(list2):
    if item == '||' and list2[index-1] == '||':
        del list2[index]
        *<some action that resarts the whole process>*

That way, if ['berry','||','||','||','pancake] is inside the list, I'll wind up with:

['berry','||','pancake'] instead.

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

忆梦 2024-09-25 14:43:23

我不确定你所说的“重新启动”是什么意思。您想从头开始迭代,还是直接跳过当前迭代?

如果是后者,那么 for 循环支持 continue 就像 while 循环一样:

for i in xrange(10):
  if i == 5:
    continue
  print i

上面将打印从 0 到 9 的数字,除了5.

如果您正在讨论从 for 循环的开头重新开始,那么除了“手动”之外没有其他办法,例如将其包装在 while 中> 循环:

should_restart = True
while should_restart:
  should_restart = False
  for i in xrange(10):
    print i
    if i == 5:
      should_restart = True
      break

上面将打印从 0 到 5 的数字,然后再次从 0 开始,等等(我知道这不是一个很好的例子)。

I'm not sure what you mean by "restarting". Do you want to start iterating over from the beginning, or simply skip the current iteration?

If it's the latter, then for loops support continue just like while loops do:

for i in xrange(10):
  if i == 5:
    continue
  print i

The above will print the numbers from 0 to 9, except for 5.

If you're talking about starting over from the beginning of the for loop, there's no way to do that except "manually", for example by wrapping it in a while loop:

should_restart = True
while should_restart:
  should_restart = False
  for i in xrange(10):
    print i
    if i == 5:
      should_restart = True
      break

The above will print the numbers from 0 to 5, then start over from 0 again, and so on indefinitely (not really a great example, I know).

心安伴我暖 2024-09-25 14:43:23
while True:
    for i in xrange(10):
        if condition(i):
            break
    else:
        break

这会做你想要的事情。为什么你想要这样做是另一回事。也许您应该看一下您的代码,并确保您没有错过明显且更简单的方法。

while True:
    for i in xrange(10):
        if condition(i):
            break
    else:
        break

That will do what you seem to want. Why you would want to do it is a different matter. Maybe you should take a look at your code and make sure you're not missing an obvious and easier way to do it.

不回头走下去 2024-09-25 14:43:23

重新启动整个过程的一些操作

一种糟糕的算法思考方式。

您只是进行过滤,即删除重复项。

而且 - 在 Python 中 - 你最高兴的是制作副本,而不是尝试执行 del。一般来说,很少有调用使用del

def unique( some_list ):
    list_iter= iter(some_list)
    prev= list_iter.next()
    for item in list_iter:
        if item != prev:
            yield prev
            prev= item
    yield prev

list( unique( ['berry','||','||','||','pancake'] ) )

some action that resarts the whole process

A poor way to think of an algorithm.

You're just filtering, i.e., removing duplicates.

And -- in Python -- you're happiest making copies, not trying to do del. In general, there's very little call to use del.

def unique( some_list ):
    list_iter= iter(some_list)
    prev= list_iter.next()
    for item in list_iter:
        if item != prev:
            yield prev
            prev= item
    yield prev

list( unique( ['berry','||','||','||','pancake'] ) )
痴骨ら 2024-09-25 14:43:23

不可避免的 itertools 版本,因为它刚刚出现在我面前:

from itertools import groupby

def uniq(seq):
    for key, items in groupby(seq):
        yield key

print list(uniq(['berry','||','||','||','pancake'])) # ['berry','||', 'pancake']
# or simply:
print [key for key, items in groupby(['berry','||','||','||','pancake'])]

The inevitable itertools version, because it just came to me:

from itertools import groupby

def uniq(seq):
    for key, items in groupby(seq):
        yield key

print list(uniq(['berry','||','||','||','pancake'])) # ['berry','||', 'pancake']
# or simply:
print [key for key, items in groupby(['berry','||','||','||','pancake'])]
金橙橙 2024-09-25 14:43:23

Continue 适用于任何循环。

Continue will work for any loop.

陌路黄昏 2024-09-25 14:43:23

continue 也适用于 for 循环。

>>> for i in range(3):
...     print 'Before', i
...     if i == 1:
...             continue
...     print 'After', i
... 
Before 0
After 0
Before 1
# After 1 is missing
Before 2
After 2

continue works in for loops also.

>>> for i in range(3):
...     print 'Before', i
...     if i == 1:
...             continue
...     print 'After', i
... 
Before 0
After 0
Before 1
# After 1 is missing
Before 2
After 2
清泪尽 2024-09-25 14:43:23

正如您所看到的,回答您的问题会导致一些相当复杂的代码。通常可以找到更好的方法,这就是为什么此类构造没有内置到语言中的原因。

如果您不习惯使用 itertools,请考虑使用此循环。它不仅比重新启动 for 循环更容易遵循,而且效率更高,因为它不会浪费时间重新检查已经跳过的项目。

L = ['berry','||','||','||','pancake']
idx=1
while idx<len(L):
    if L[idx-1]==L[idx]:
        del L[idx]
    else:
        idx+=1

As you can see answering your question leads to some rather convoluted code. Usually a better way can be found, which is why such constructs aren't built into the language

If you are not comfortable using itertools, consider using this loop instead. Not only is it easier to follow than your restarting for loop, it is also more efficient because it doesn't waste time rechecking items that have already been passed over.

L = ['berry','||','||','||','pancake']
idx=1
while idx<len(L):
    if L[idx-1]==L[idx]:
        del L[idx]
    else:
        idx+=1
很酷不放纵 2024-09-25 14:43:23
def remove_adjacent(nums):
     return [a for a,b in zip(nums, nums[1:]+[not nums[-1]]) if a != b]

example = ['berry','||','||','||','pancake']

example = remove_adjacent(example)
print example
""" Output:
['berry', '||', 'pancake']
"""

顺便说一句,这是重复 从 a 中删除相邻的重复元素列表

def remove_adjacent(nums):
     return [a for a,b in zip(nums, nums[1:]+[not nums[-1]]) if a != b]

example = ['berry','||','||','||','pancake']

example = remove_adjacent(example)
print example
""" Output:
['berry', '||', 'pancake']
"""

And by the way this is repeating of Remove adjacent duplicate elements from a list

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文