Python - Way to restart a for loop, similar to “co

2020-01-29 08:40发布

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!

8条回答
Evening l夕情丶
2楼-- · 2020-01-29 09:18
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

查看更多
不美不萌又怎样
3楼-- · 2020-01-29 09:20

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'])]
查看更多
爷、活的狠高调
4楼-- · 2020-01-29 09:22

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).

查看更多
男人必须洒脱
5楼-- · 2020-01-29 09:25

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
查看更多
forever°为你锁心
6楼-- · 2020-01-29 09:31
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.

查看更多
三岁会撩人
7楼-- · 2020-01-29 09:31

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'] ) )
查看更多
登录 后发表回答