readlines()是否在Python 3中返回列表或迭代器?

sna*_*ile 32 python iterator readlines python-3.x

我读过"潜入Python 3","readlines()方法现在返回一个迭代器,因此它与Python 2中的xreadlines()一样高效".见这里:http://diveintopython3.org/porting-code-to-python-3-with-2to3.html.我不确定这是真的,因为他们在这里没有提到它:http://docs.python.org/release/3.0.1/whatsnew/3.0.html.我该怎么检查?

Sco*_*ths 31

readlines方法不返回Python 3中的迭代器,它返回一个列表

Help on built-in function readlines:

readlines(...)
    Return a list of lines from the stream.
Run Code Online (Sandbox Code Playgroud)

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

>>> type(f.readlines())
<class 'list'>
Run Code Online (Sandbox Code Playgroud)

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


xreadlines文件对象成为自己的迭代器以来,Python 2.3已被弃用.获得相同效率的xreadlines方法而不是使用

 for line in f.xreadlines():
Run Code Online (Sandbox Code Playgroud)

你应该简单地使用

 for line in f:
Run Code Online (Sandbox Code Playgroud)

这可以获得你想要的迭代器,并且有助于解释为什么readlines不需要在Python 3中改变它的行为 - 它仍然可以返回一个完整的列表,使用line in f成语给出迭代方法,并且xreadlines已经删除了long-deprecated 完全.

  • 这个答案更好,因为它还提供了隐含问题的答案:如何在文件上获得迭代器? (3认同)
  • 我大约一周前才发现文件是他们自己的迭代器:(我想这对我来说是正确的,因为没有看到1.5以来的教程/发行说明. (2认同)

Joh*_*hin 24

像这样:

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.

>>>
Run Code Online (Sandbox Code Playgroud)


Jac*_*nor 7

其他人已经说了很多,但只是为了推动这一点,普通文件对象是他们自己的迭代器.因此,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)
Run Code Online (Sandbox Code Playgroud)