如何通过生成器或其他方法无限循环Python中的迭代器? [英] How can I infinitely loop an iterator in Python, via a generator or other?
问题描述
据我了解,使用Generator是实现此类目标的最佳方法,但我愿意接受建议.
It's my understanding that using a Generator is the best way to achieve something like this, but I'm open to suggestions.
具体来说,一个用例是:我想在另一个列表的旁边打印任意长度的某些项目,并在必要时截断初始迭代器.
Specifically, one use case is this: I'd like to print some items alongside another list, of an arbitrary length, truncating the initial iterator as necessary.
这里正在运行的python代码演示了我想要的确切示例行为:
Here is working python code that demonstrates the exact example behavior I desire:
def loop_list(iterable):
"""
Return a Generator that will infinitely repeat the given iterable.
>>> l = loop_list(['sam', 'max'])
>>> for i in range(1, 11):
... print i, l.next()
...
1 sam
2 max
3 sam
4 max
5 sam
6 max
7 sam
8 max
9 sam
10 max
>>> l = loop_list(['sam', 'max'])
>>> for i in range(1, 2):
... print i, l.next()
...
1 sam
"""
iterable = tuple(iterable)
l = len(iterable)
num = 0
while num < l:
yield iterable[num]
num += 1
if num >= l:
num = 0
问题/我的问题
您可能已经注意到,这仅适用于实现__getitem__
的列表/元组/可迭代对象(如果我没记错的话).理想情况下,我希望能够传递任何可迭代的对象,并接收可以正确循环其内容的生成器.
The Problem / My Question
As you may have noticed, this only works on lists/tuples/iterables that implement __getitem__
(if I'm not mistaken). Ideally, I'd like to be able to pass any iterable, and receive a generator that can properly loop over it's content.
如果有更好的方法来执行这样的操作,不使用,我也很好.
If there's a better way to do something like this without a generator, I'm fine with that as well.
推荐答案
您可以使用 itertools.cycle
(链接页面上包含源代码).
You can use itertools.cycle
(source included on linked page).
import itertools
a = [1, 2, 3]
for element in itertools.cycle(a):
print element
# -> 1 2 3 1 2 3 1 2 3 1 2 3 ...
这篇关于如何通过生成器或其他方法无限循环Python中的迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!