Python懒惰迭代器 [英] Python lazy iterator

查看:67
本文介绍了Python懒惰迭代器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解如何以及何时对迭代器表达式求值.以下似乎是一个懒惰的表达:

I am trying to understand how and when iterator expressions get evaluated. The following seems to be a lazy expression:

g = (i for i in range(1000) if i % 3 == i % 2)

这个,但是在构造上失败了:

This one, however fails on construction:

g = (line.strip() for line in open('xxx', 'r') if len(line) > 10)

我没有名为"xxx"的文件.但是,由于这件事很懒,为什么它会这么快失败呢?

I do not have the file named 'xxx'. However, since this thing is lazy, why is it failing so soon?

谢谢.

EDI:哇,我做了个懒人!

EDI: Wow, I made a lazy one!

g = (line.strip() for i in range(3) for line in open(str(i), 'r'))

推荐答案

文档:

生成器中使用的变量 表达式在 next()时的单独作用域 为生成器调用方法 对象(与 普通发电机).但是,in 最左边的for的表达式 子句会立即在 当前范围,以便出现错误 它产生的任何东西都可以被看到 代码中的其他可能错误 处理生成器表达式.

Variables used in the generator expression are evaluated lazily in a separate scope when the next() method is called for the generator object (in the same fashion as for normal generators). However, the in expression of the leftmost for clause is immediately evaluated in the current scope so that an error produced by it can be seen before any other possible error in the code that handles the generator expression.

这篇关于Python懒惰迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆