![](/img/trans.png)
[英]How to access the next item of a list, inside the (for item in list) loop ? (Python 3)
[英]Setting the list item in a Python for loop
阿羅哈大家,
假設我有一個列表,我想列出該列表中的項目,然后打印出來,然后我會這樣做。
list = ['a', 'b', 'c']
for item in list:
print item
這應該導致這一點。
a
b
c
很簡單。
我的問題是,當某個事件發生時,例如達到'b',那么我希望循環繼續迭代,但是從剛剛到達的點再次開始。 因此輸出就是這個。
a
b
b
c
我試過一個解決方案,但是沒有用。
list = ['a', 'b', 'c']
for item in list:
print item
index = list.index(item)
if item == 'b':
item = list[index - 1]
我曾希望這會將項目設置為'a',因此下一次迭代將繼續回到'b',但事實並非如此。
在此先感謝您的幫助。
為什么不是以下內容:
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
您可以使用數字for循環輕松完成此操作。 一種更復雜的方法也可以通過編寫自己的生成器類來設計,當被告知時,它會再次產生相同的元素。
編輯:好的,這是復雜的方式!
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.