gpt4 book ai didi

python - 创建无限循环生成器的巧妙方法?

转载 作者:行者123 更新时间:2023-11-28 20:39:21 24 4
gpt4 key购买 nike

我想要一个无限循环遍历值列表的生成器。

这是我的解决方案,但我可能遗漏了一个更明显的解决方案。

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

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)

用途:

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
...

正如我所说,我可能缺少一种简单的方法来做同样的事情,我很乐意学习。有没有更简洁的方法?

此外,我是否应该担心这里发生的所有令人难以置信的无穷大的内存消耗,还是我的代码一切都很酷?

最佳答案

您可以使用 itertools.cycle达到同样的效果

Make an iterator returning elements from the iterable and saving a copy of each. When the iterable is exhausted, return elements from the saved copy.

强调我的。您唯一关心的内存是保存迭代器返回的每个项目的副本。

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

关于python - 创建无限循环生成器的巧妙方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38415014/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com