【问题标题】:Does readlines() return a list or an iterator in Python 3?readlines() 在 Python 3 中是否返回列表或迭代器?
【发布时间】:2011-04-02 06:09:03
【问题描述】:

我在“深入 Python 3”中读到:

readlines() 方法现在返回一个迭代器,因此它与 Python 2 中的 xreadlines() 一样高效”。

请参阅:Appendix A: Porting Code to Python 3 with 2to3: A.26 xreadlines() I/O method

我不确定这是不是真的,因为他们在这里没有提到:http://docs.python.org/release/3.0.1/whatsnew/3.0.html。如何检查?

【问题讨论】:

    标签: python iterator python-3.x readlines


    【解决方案1】:

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

    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 已被完全删除。

    【讨论】:

    • 我希望任何使用for line in f.xreadlines(): 的人都会在几年前将其转换为for line in f:
    • @John Machin:我也希望如此(尽管可能没想到!)我并不是要暗示 xreadlines 是 Python 2 中的首选方式——它是当引入文件作为迭代器方法时,在 Python 2.3 中已弃用。我只是想说明它可以在 Python 3 中删除的原因。
    • 大约一周前我才发现文件是它们自己的迭代器:(我想这对我来说是正确的,因为我从 1.5 开始就不看教程/发行说明了。
    • 这个答案更好,因为它还提供了对隐含问题的答案:如何获得文件的迭代器?
    【解决方案2】:

    像这样:

    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.
    
    >>>
    

    【讨论】:

      【解决方案3】:

      其他人已经说了这么多,但只是为了说明问题,普通文件对象是它们自己的迭代器。所以让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)
      

      【讨论】:

      • 并不完全愚蠢,因为readlineshint 参数(在读取hint 字符/字节后停止读取新行)在处理非常大的文件时可能很有用。这也正是您需要迭代器而不是列表的时候。
      猜你喜欢
      • 1970-01-01
      • 2014-11-27
      • 2015-03-09
      • 2015-09-23
      • 1970-01-01
      • 2014-02-01
      • 2015-09-06
      • 2021-02-17
      • 2018-02-05
      相关资源
      最近更新 更多