原生无限范围?

jac*_*rdy 21 python

python是否具有无限整数系列的本机可迭代?

我试过range(float('inf'))iter(int),但既不工作.

我显然可以实现自己的发电机

def int_series(next=1):
    while True:
        next += 1
        yield next
Run Code Online (Sandbox Code Playgroud)

但这感觉就像应该存在的东西.

use*_*ica 37

是.它是itertools.count:

>>> import itertools
>>> x = itertools.count()
>>> next(x)
0
>>> next(x)
1
>>> next(x)
2
>>> # And so on...
Run Code Online (Sandbox Code Playgroud)

您可以指定startstep参数,但stop不是一个选项(这是什么xrange):

>>> x = itertools.count(3, 5)
>>> next(x)
3
>>> next(x)
8
>>> next(x)
13
Run Code Online (Sandbox Code Playgroud)


Ash*_*ary 15

你可以用itertools.count它.

for x in itertools.count():
    # do something with x infinite times
Run Code Online (Sandbox Code Playgroud)

如果您不想使用返回的整数count(),那么最好使用itertools.repeat:

for _ in itertools.repeat(None):
     # do something infinite times
Run Code Online (Sandbox Code Playgroud)

  • 如果你不想要整数,那么`while True`更合适. (7认同)
  • 如果这个微小的开销真的很重要,`while 1`被编译成无条件跳转,这甚至比for循环更快.最有可能的是,循环体所占用的时间将占主导地位,差异无关紧要. (6认同)
  • 开销对于一个无限次运行的循环无关紧要;-) (4认同)
  • @ user2357112在python3.3`中,True`编译为**与'while 1'相同的指令(即`SETUP_LOOP` +`JUMP_ABSOLUTE`).在python2.7中有一个区别.我没有以前版本的python3来检查,但我相信已经在python3.0中它们是等价的. (3认同)