是否有无限发电机的表达式? [英] Is there an expression for an infinite generator?
问题描述
是否存在可以产生无限元素的直接生成器表达式?
Is there a straight-forward generator expression that can yield infinite elements?
这是一个纯粹的理论问题。这里不需要实用答案:)
This is a purely theoretical question. No need for a "practical" answer here :)
例如,很容易制作一个有限的发电机: / p>
For example, it is easy to make a finite generator:
my_gen = (0 for i in xrange(42))
然而,要创建一个无限的,我需要用虚假函数污染我的命名空间:
However, to make an infinite one I need to "pollute" my namespace with a bogus function:
def _my_gen():
while True:
yield 0
my_gen = _my_gen()
在单独的文件中执行操作并且 import
-ing稍后不计算。
Doing things in a separate file and import
-ing later doesn't count.
我也知道 itertools.repeat
就是这样做的。我很好奇是否有没有这个的单线解决方案。
I also know that itertools.repeat
does exactly this. I'm curious if there is a one-liner solution without that.
推荐答案
for x in iter(int, 1): pass
- 双参数
iter
=零参数可调用+标记值 -
int()
始终返回0
- Two-argument
iter
= zero-argument callable + sentinel value int()
always returns0
因此, iter(int,1 )
是一个无限的迭代器。这个特定的主题显然有很多变化(特别是一旦你将 lambda
添加到混音中)。特别注意的一个变体是 iter(f,object())
,因为使用新创建的对象作为sentinel值几乎保证无限迭代器,无论使用哪个可调用对象第一个论点。
Therefore, iter(int, 1)
is an infinite iterator. There are obviously a huge number of variations on this particular theme (especially once you add lambda
into the mix). One variant of particular note is iter(f, object())
, as using a freshly created object as the sentinel value almost guarantees an infinite iterator regardless of the callable used as the first argument.
这篇关于是否有无限发电机的表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!