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 完全.
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)
其他人已经说了很多,但只是为了推动这一点,普通文件对象是他们自己的迭代器.因此,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)
归档时间: |
|
查看次数: |
30160 次 |
最近记录: |