代码之家  ›  专栏  ›  技术社区  ›  snakile

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

  •  29
  • snakile  · 技术社区  · 14 年前

    我在“dive into 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 . 我怎么检查?

    3 回复  |  直到 12 年前
        1
  •  20
  •   John Machin Santi    14 年前

    这样地:

    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.
    
    >>>
    
        2
  •  28
  •   Scott Griffiths    14 年前

    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 当文件对象成为自己的迭代器时。获得相同效率的方法 X线 不是使用

     for line in f.xreadlines():
    

    you should use simply

     for line in f:
    

    这将得到您想要的迭代器,并有助于解释为什么 readlines 不需要在python 3中更改其行为-它仍然可以返回完整的列表,其中 line in f 给出迭代方法的习语,以及长期以来不赞成使用的 X线 已完全删除。

        3
  •  7
  •   Jack O'Connor    12 年前

    其他人已经说过了很多,但只是为了把点带回家,普通的文件对象是他们自己的迭代器。所以拥有 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)