我搜索了count(),但只找到了列表和对象的方法,我只是不明白这行是怎么回事 self._candidates = count(1) 工作和它的意义。 我们试图计算1的对象在哪里?以及它的进一步使用 self._candidates.next() 我主要用java编写代码,尽管我知道基本的python。 代码如下:
self._candidates = count(1)
self._candidates.next()
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
itertools.count
from itertools import count
Generators 在Python中与 Iterator count(1) 返回从1开始向上计数的生成器:
Iterator
count(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)
counter.next()
next(counter)