首页 > 解决方案 > 如何为字符串列表创建迭代器

问题描述

我有一个包含字符串元素的列表,最后我想收到:

a hello
b hello
c hello
d hello

我有这个代码:

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

class Iterator:

    def __init__(self, start, end):
        self.start=start
        self.end=end

    def __iter__(self):
        return self

    def __next__(self):
        self.start += ' hello'
        if self.start == list[-1]:
          raise StopIterration 
        return self.start

if __name__ == '__main__':
    for item in Iterator(list[0], list[-1]):
        print(item)

但是,methond __next__CANNOT MOVE FROM list[0]to list[1],python 开始发疯,在 中添加十亿个“ hellolist[0],甚至无法停止程序,所以现在是地狱循环。问题是:

  1. 将十亿个“你好”添加到list[0],而不是移动到list[1]
  2. 根本没有完成程序,尽管我写了什么是完成的条件。

在此处输入图像描述

标签: pythonpython-3.xiterator

解决方案


您的实例Iterator根本与列表无关;您使用列表创建实例无关紧要;Iterator.__init__只看到两个字符串值。

__init__需要对列表本身的引用以供__next__. 此外,hello是您附加到 的返回值的__next__东西,而不是每次调用时都需要附加到内部状态的东西__next__

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

class Iterator:

    def __init__(self, lst):
        self.lst = lst
        self.start = 0

    def __iter__(self):
        return self

    def __next__(self):
        try:
            value = self.lst[self.start]
        except IndexError:
            raise StopIteration
        self.start += 1

        return value + ' hello'

if __name__ == '__main__':
    for item in Iterator(list):
        print(item)

推荐阅读