首页 > 解决方案 > itertools.cycle(iterable) vs while True

问题描述

I was recently asked to do this task (school) :

Write a loop generator, which takes as parameter a finite iterable, and generates in infinite loop the iterable

So I did :

import itertools
def loop(l):
    for eleme‍‌​‍‌nt in itertools.cycle(l):
        yield element

and one of my classmate did :

def loop(l):
    while True:
​‍         for element in l:
            yield element

I'd like to know what are the main differences between the two and if there is a more "pythonic" way to write something simple as this.

标签: pythonpython-3.xloopsitertools

解决方案


你是对的,这里对经典循环itertools.cycle并不感兴趣。while True

另一方面,它对无限生成器推导有很大帮助,在这种情况下,您无法创建无限循环,因为它只允许for、 测试和函数调用。无限期生成列表平方值的示例:

generator = (x*x for x in itertools.cycle(l))

当然,您总是可以通过以下方式缩短当前代码:

def loop(l):
    yield from itertools.cycle(l)

甚至:

loop = itertools.cycle

推荐阅读