本机无限范围?

2024-04-29 08:20:23 发布

您现在位置:Python中文网/ 问答频道 /正文

python有无限整数序列的原生iterable吗?

我试过range(float('inf'))iter(int),但都没用。

很明显,我可以按照

def int_series(next=1):
    while True:
        next += 1
        yield next

但这感觉好像已经存在了。


Tags: truedefrange序列整数floatiterablenext
0条回答
网友
1楼 · 发布于 2024-04-29 08:20:23

你可以用^{}来做这个。

for x in itertools.count():
    # do something with x infinite times

如果不想使用count()返回的整数,则最好使用^{}

for _ in itertools.repeat(None):
     # do something infinite times
网友
2楼 · 发布于 2024-04-29 08:20:23

是的。是^{}

>>> import itertools
>>> x = itertools.count()
>>> next(x)
0
>>> next(x)
1
>>> next(x)
2
>>> # And so on...

您可以指定startstep参数,尽管stop不是一个选项(这就是xrange的用途):

>>> x = itertools.count(3, 5)
>>> next(x)
3
>>> next(x)
8
>>> next(x)
13

相关问题 更多 >