readlines() 在 Python 3 中返回列表还是迭代器?
我在“Dive into Python 3”中读到:
“
readlines()
方法现在返回一个迭代器,因此它与 Python 2 中的xreadlines()
一样高效”。
请参阅: 附录 A:使用 2to3 将代码移植到 Python 3 :A.26 xreadlines() I/O方法。
我不确定这是真的,因为他们没有在这里提及: http://docs.python.org/release/3.0.1/whatsnew/3.0.html。我该如何检查?
I've read in "Dive into Python 3" that:
"The
readlines()
method now returns an iterator, so it is just as efficient asxreadlines()
was in Python 2".
See: Appendix A: Porting Code to Python 3 with 2to3: A.26 xreadlines() I/O method.
I'm not sure that's true because they don't mention it here: http://docs.python.org/release/3.0.1/whatsnew/3.0.html . How can I check that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
readlines 方法在 Python 3 中不返回迭代器,它返回一个列表
要检查,只需从交互式会话中调用它 - 它将返回一个列表,而不是迭代器:
在这种情况下,深入 Python 似乎是错误的。
xreadlines
已自 Python 2.3 起已弃用对象成为它们自己的迭代器。获得与 xreadlines 相同效率的方法是使用你应该简单地使用
这会让你得到你想要的迭代器,并有助于解释为什么readlines不需要改变它在Python 3中的行为 - 它仍然可以返回一个完整的列表,其中
line in f
习惯用法给出了迭代方法,并且长期弃用的xreadlines
已被完全删除。The readlines method doesn't return an iterator in Python 3, it returns a list
To check, just call it from an interactive session - it will return a list, rather than an iterator:
Dive into Python appears to be wrong in this case.
xreadlines
has been deprecated since Python 2.3 when file objects became their own iterators. The way to get the same efficiency asxreadlines
is instead of usingyou should use simply
This gets you the iterator that you want, and helps to explain why
readlines
didn't need to change its behaviour in Python 3 - it can still return a full list, with theline in f
idiom giving the iterative approach, and the long-deprecatedxreadlines
has been removed completely.像这样:
Like this:
其他人已经说过了,但为了说明这一点,普通文件对象是它们自己的迭代器。因此让 readlines() 返回迭代器是愚蠢的,因为它只会返回您调用它的文件。您可以使用 for 循环来迭代文件,就像 Scott 所说,您也可以将它们直接传递给 itertools 函数:
Others have said as much already, but just to drive the point home, ordinary file objects are their own iterators. So having
readlines()
return an iterator would be silly, because it would just return the file you called it on. You can use afor
loop to iterate over a file, like Scott said, and you can also pass them straight to itertools functions: