python - 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 element 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.
解决方案
你是对的,这里对经典循环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
推荐阅读
- python - 试图产生正确的递归
- django - 有什么方法可以清除浏览器上的会话或在 Django 中关闭选项卡,因为 SESSION_EXPIRE_AT_BROWSER_CLOSE = True 根本不起作用?
- bash - 如何在 Bash 中验证逗号分隔的选项参数?
- swiftui - 如何在圆圈中间放置加号
- java - 添加最新的 Firebase 依赖项后应用程序崩溃
- android - 如何在android编程中按文件夹路径打开文件?
- python - 如何从基于 Keras 的基于词的神经语言模型中获得输出的困惑度分数
- django-channels - Django Channels / Daphne 内部服务器错误:“模块”对象不可调用
- asp.net-core - Serilog 未在 Ubuntu 上写入文件
- python - 无法为 Python 3.8.10 创建虚拟环境