我想做一个发电机。该生成器应该采用可迭代的。这基本上是为了让我可以将生成器插入现有框架中。
这是我到目前为止得到的代码。
class Iter1(object):
def __init__(self, iterable=None):
self.iterable = iterable
def __iter__(self):
if self.iterable is None:
self.iterable = Iter2()
return self.iterable
def next(self):
for thing in self.iterable:
yield thing
class Iter2(object):
DEFAULT_PATH = r"/Users/Documents/stuff.txt"
def __init__(self, path=None):
self.path = path or self.DEFAULT_PATH
def __iter__(self):
return self
def next(self):
with open(self.path, 'r') as f:
for line in f:
yield line
if __name__ == "__main__":
iterable = Iter1()
for thing in iterable:
print(thing)
这段代码有两个问题。首先,返回(产生)的不是文件中的一行,而是另一个生成器对象。
第二个是它不返回文件中的行数,它只返回无限行数。我明白这是因为每次我在 Iter2
中调用 next
时,我都会再次打开该文件,但是我不明白如何在不加载整个文件的情况下生成每一行文件存入内存。
最佳答案
Iterator objects returned by either form of iter() have a next() method. This method either returns the next value in the iteration, or raises StopIteration (or a derived exception class) to signal the end of the iteration. Any other exception should be considered to signify an error and should be propagated normally, not taken to mean the end of the iteration.
您正在从 next()
返回一个迭代器,这就是它无法按预期工作的原因。相反,您应该在每次调用 next()
时返回一个值。
此外,让 __iter__()
返回 self
有点奇怪。通常认为多次调用 iter(sequence)
将返回多个新的迭代器,每个迭代器都从序列的开头开始,但您的代码并非如此。
关于python - 如何制作一个由另一个发电机组成的发电机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42545779/