简体   繁体   中英

Setting the list item in a Python for loop

Aloha everyone,

Say I have a list and I want to list through the items in that list printing them out as I go, then I would do this.

list = ['a', 'b', 'c']

for item in list:
   print item

This should result in this.

a
b
c

Simple enough.

My issue is that when a certain event occurs, for example reaching a 'b', then I want the loop to continue iterating but start again from the point it has just reached. Therefore the output would be this.

a
b
b
c

I had attempted one solution which went along the lines of this but didn't work.

list = ['a', 'b', 'c']

for item in list:
   print item

   index = list.index(item)
   if item == 'b':
      item = list[index - 1]

I had hoped that this would set the item to 'a' so the next iteration would continue on back through to 'b', but that wasn't the case.

Thanks in advance for any help.

Why not the following:

for item in lst:
    dostuff()
    if item=="b":
        dostuff()
>>> def my_iter(seq):
...   for item in seq:
...       yield item
...       if item == 'b':
...         yield item
...
>>> for item in my_iter('abc'):
...     print item
...
a
b
b
c

You can easily do this using a numeric for-loop. A way-more-complicated method could also be devised by writing your own generator class which would yield the same element again when told to do so.

Edit: OK, here's the complicated way!

class Repeater(object):
    def __init__(self, sequence):
        self._sequence = sequence

    def __iter__(self):
        for item in self._sequence.__iter__():
            self._repeat = False
            yield item
            if self._repeat:
                yield item

    def repeat(self):
        self._repeat = True

list = ['a', 'b', 'c']
repeater = Repeater(list)

for item in repeater:
    print item
    if (item == 'b'):
        repeater.repeat();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM