readlines()在Python3中返回列表还是迭代器?

2024-04-25 23:02:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我在“Diveintopython3”中读到,“readlines()方法现在返回一个迭代器,所以它和Python2中的xreadlines()一样高效”。请看这里:http://diveintopython3.org/porting-code-to-python-3-with-2to3.html。我不确定这是真的,因为他们在这里没有提到:http://docs.python.org/release/3.0.1/whatsnew/3.0.html。我该怎么查?


Tags: to方法orghttpdocsreleasehtmlwith
3条回答

像这样:

Python 3.1.2 (r312:79149, Mar 21 2010, 00:41:52) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open('/junk/so/foo.txt')
>>> type(f.readlines())
<class 'list'>
>>> help(f.readlines)
Help on built-in function readlines:

readlines(...)
    Return a list of lines from the stream.

    hint can be specified to control the number of lines read: no more
    lines will be read if the total size (in bytes/characters) of all
    lines so far exceeds hint.

>>>

其他人已经说过很多了,但是仅仅为了说明问题,普通的文件对象是它们自己的迭代器。所以让readlines()返回迭代器是愚蠢的,因为它只会返回您调用它的文件。您可以使用for循环遍历文件,如Scott所说,还可以将它们直接传递给itertools函数:

from itertools import islice
f = open('myfile.txt')
oddlines = islice(f, 0, None, 2)
firstfiveodd = islice(oddlines, 5)
for line in firstfiveodd:
  print(line)

readlines方法在Python 3中不返回迭代器,而是返回一个列表

Help on built-in function readlines:

readlines(...)
    Return a list of lines from the stream.

要检查,只需从交互式会话调用它-它将返回一个列表,而不是迭代器:

>>> type(f.readlines())
<class 'list'>

在这种情况下,潜入Python似乎是错误的。


当文件对象成为它们自己的迭代器时,xreadlines一直是deprecated since Python 2.3。获得与xreadlines相同效率的方法不是使用

 for line in f.xreadlines():

you should use simply

 for line in f:

这将为您提供所需的迭代器,并有助于解释为什么readlines不需要在Python 3中更改其行为-它仍然可以返回完整的列表,而line in f习惯用法给出了迭代方法,并且已完全删除了长期不推荐的xreadlines

相关问题 更多 >