python - 在不使用生成器函数的情况下,如何在 Python 中实现与 itertools.count 等效的迭代器?

标签 python iterator generator

使用生成器函数,可以这样实现itertools.count(来自documentation):

def count(start=0, step=1):
    # count(10) --> 10 11 12 13 14 ...
    # count(2.5, 0.5) -> 2.5 3.0 3.5 ...
    n = start
    while True:
        yield n
        n += step

我正在尝试寻找如何在没有生成器函数的情况下实现类似的迭代器。

class Count:
    def __init__(self, start=0, step=1):
        self.c = start
        self.step = step

    def __iter__(self):
        return self

    def __next__(self):
        n = self.c
        self.c += self.step
        return n

这是实现吗?

当然,它没有任何实际意义,重点只是了解如何使用生成器实现它。

最佳答案

您可以使用collections.abc.Iterator以更少的代码实现计数

from collections.abc import Iterator

class count(Iterator):
    def __init__(self, start=0, step=1):
        self.c, self.step = start-step, step

    def __next__(self):
        self.c += self.step
        return self.c

关于python - 在不使用生成器函数的情况下,如何在 Python 中实现与 itertools.count 等效的迭代器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54487250/

相关文章:

python - 使用 glGetFloatv 检索 pyglet 中的模型 View 矩阵

python - 动态函数创建和函数体评估

typescript - yielded put 操作未分派(dispatch)存储在回调中

python - 从 Python 列表中获取前 n 个唯一元素

python Pandas : How to groupby and count and select a portion of counts?

c++ - 在类模板中创建指向映射的迭代器

c++ - 将映射中的对象(指针)输出到二进制文件

c++ - 使用迭代器查找 vector 的中间元素 - C++

python - 如何使用生成器在 Python 中生成不带 "reverse duplicates"的列表排列

python - 查找重复行,将某一列乘以重复行数,删除重复行