一种创建无限循环发生器的巧妙方法?

Agu*_*guy 2 python python-3.x

我想要一个通过值列表无限循环的生成器.

这是我的解决方案,但我可能会错过一个更明显的解决方案.

成分:一个生成器函数,用于展平无限嵌套列表,以及一个附加到自身的列表

def ge(x):
    for it in x:
        if isinstance(it, list):
            yield from ge(it)
        else:
            yield(it)


def infinitecyclegenerator(l):
    x = l[:]
    x.append(x)
    yield from ge(x)
Run Code Online (Sandbox Code Playgroud)

使用:

g = infinitecyclegenerator([1,2,3])

next(g) #1
next(g) #2
next(g) #3
next(g) #1
next(g) #2
next(g) #3
next(g) #1
...
Run Code Online (Sandbox Code Playgroud)

正如我所说的,我可能会错过一个琐碎的方式来做同样的事情,我会很乐意学习.有更简洁的方式吗?

此外,我是否应该担心内存消耗,这里有令人难以置信的无限无敌,或者我的代码是否一切都很酷?

Mos*_*oye 7

您可以使用itertools.cycle来实现相同的结果

使迭代器返回迭代中的元素并保存每个元素的副本.当iterable耗尽时,返回保存副本中的元素 .

强调我的.您对内存的唯一顾虑是保存迭代器返回的每个项目的副本.

>>> from itertools import cycle
>>> c = cycle([1,2,3])
>>> next(c)
1
>>> next(c)
2
>>> next(c)
3
>>> next(c)
1
>>> next(c)
2
>>> next(c)
3
Run Code Online (Sandbox Code Playgroud)