Python 使用 count() 初始化迭代器

Python Primes iterator using count()

我想了解素数迭代器的工作原理,代码取自讲座。 我搜索了 count() 但只找到了列表、对象的方法,我只是不明白 self._candidates = count(1) 行的工作原理及其含义。 我们要计算 1 的对象在哪里?并且进一步使用它 self._candidates.next() 也很混乱。 尽管知道基本的 python,但我主要使用 java 编写代码。 这是代码:

class Primes(object):
    def __init__(self):
        self._candidates = count(1)
    def __iter__(self): return self
    def next(self):
        item = self._candidates.next()
        if item > 1:
            self._candidates = FilterMultiplies(self._candidates, item)
        return item

class FilterMultiplies(object):def __init__(self, seq, n):
    self._seq = iter(seq)
        self._n = n
    def __iter__(self): return self
    def next(self):
        item = self._seq.next()
        while item % self._n == 0:
            item = self._seq.next()
        return item

大概这是itertools.count,还有一行

from itertools import count

列表中缺少。

Python 中的

Generators 与 Java 中的 Iterator 相当。调用 count(1) returns 一个从 1 开始向上计数的生成器:

>>> from itertools import count
>>> counter = count(1)
>>> counter.next()
1
>>> counter.next()
2
>>> counter.next()
3

请注意 counter.next() 只是 Python 2。为了与 Python 2 和 3 兼容,请改用 next(counter)