是否有无限迭代器的表达式? [英] Is there an expression for an infinite iterator?

查看:58
本文介绍了是否有无限迭代器的表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否存在可以生成无限迭代器的简单表达式?

Is there a straight-forward expression that can produce an infinite iterator?

这是一个纯粹的理论问题.不需要实用"的工具.在这里回答:)

This is a purely theoretical question. No need for a "practical" answer here :)

例如,很容易使用生成器表达式来进行有限迭代器:

For example, it is easy to use a generator expression to make a finite iterator:

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不计算在内.

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 returns 0
    • 因此,iter(int, 1)是无限迭代器.显然,此特定主题有很多变体(尤其是在您将lambda添加到组合中之后).特别注意的一个变体是iter(f, object()),因为使用新创建的对象作为哨兵值几乎可以保证无限迭代器,而与用作第一个参数的可调用对象无关.

      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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆