python - 如何为字符串列表创建迭代器
问题描述
我有一个包含字符串元素的列表,最后我想收到:
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 开始发疯,在 中添加十亿个“ hello
” list[0]
,甚至无法停止程序,所以现在是地狱循环。问题是:
- 将十亿个“你好”添加到
list[0]
,而不是移动到list[1]
。 - 根本没有完成程序,尽管我写了什么是完成的条件。
解决方案
您的实例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)
推荐阅读
- r - kableExtra in for - 循环
- sublimetext - Sublime Text 3 插件 HTML 弹出窗口渲染
- google-chrome - Google Chrome Inspector 的图像大小是什么意思?
- python - Python字典排序列表
- sql - 思考具有两个外键的一对多或多对多关系的正确方法是什么?
- visual-studio-code - visual studio code + ubuntu + 中文名字Short
- python - 如何使用 ffmpeg-python 将视频剪切到一定长度并添加介绍视频?
- c++ - c++ winsock接受抛出的异常
- php - PHP,fopen() 无法从站点的根目录创建新文件
- asp.net - Recaptcha 停止在我的一半网站上工作?