简体   繁体   English

在Python for循环中设置列表项

[英]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. 我的问题是,当某个事件发生时,例如达到'b',那么我希望循环继续迭代,但是从刚刚到达的点再次开始。 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. 我曾希望这会将项目设置为'a',因此下一次迭代将继续回到'b',但事实并非如此。

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. 您可以使用数字for循环轻松完成此操作。 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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