python - 如何制作一个由另一个发电机组成的发电机

标签 python python-2.7 iterator generator

我想做一个发电机。该生成器应该采用可迭代的。这基本上是为了让我可以将生成器插入现有框架中。

这是我到目前为止得到的代码。

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 时,我都会再次打开该文件,但是我不明白如何在不加载整个文件的情况下生成每一行文件存入内存。

最佳答案

PEP 234 -- Iterators :

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/

相关文章:

python - 用递归找出一对中的目标差异

python - 链式重载比较运算符

c++ - 映射迭代器与运算符不匹配

c++ - 如何减轻在 C++ 中检查迭代器值的语法开销?

php - 一个对象应该实现迭代器还是包含另一个实现迭代器的对象

python - 返回多边形 geopandas 内的点列表

python - 如何用图像中每个像素的颜色绘制图形?

python-2.7 - socket.send() 引发 AttributeError : 'tuple' object has no attribute 'send'

python - 从数据框中删除包含特定字符串的行

windows - 运行 32 位 Python 2.7 构建的 64 位 Windows 10 的 python-magic 安装挑战