您可以使用itertools.islice() https://docs.python.org/2/library/itertools.html#itertools.islice给予count
an end:
from itertools import count, islice
for i in islice(count(start_value), end_value - start_value):
islice()
raises StopIteration
after end_value - start_value
值已被迭代。
支持 1 以外的步长并将其全部放在一个函数中将是:
from itertools import count, islice
def irange(start, stop=None, step=1):
if stop is None:
start, stop = 0, start
length = 0
if step > 0 and start < stop:
length = 1 + (stop - 1 - start) // step
elif step < 0 and start > stop:
length = 1 + (start - 1 - stop) // -step
return islice(count(start, step), length)
然后使用irange()
就像你会用的range()
or xrange()
,除了你现在可以使用Pythonlong
整数:
>>> import sys
>>> for i in irange(sys.maxint, sys.maxint + 10, 3):
... print i
...
9223372036854775807
9223372036854775810
9223372036854775813
9223372036854775816