我需要逐行读取一个文件,我需要查看"下一行",所以首先我将文件读入列表,然后循环浏览列表...不知怎的,这似乎很粗鲁,建立列表可能是变得昂贵.
for line in open(filename, 'r'):
lines.append(line[:-1])
for cn in range(0, len(lines)):
line = lines[cn]
nextline = lines[cn+1] # actual code checks for this eof overflow
Run Code Online (Sandbox Code Playgroud)
必须有更好的方法来迭代线,但我不知道如何向前看
您可能正在寻找类似itertools 的成对配方.
from itertools import tee, izip
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return izip(a, b)
with open(filename) as f: # Remember to use a with block so the file is safely closed after
for line, next_line in pairwise(f):
# do stuff
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2775 次 |
| 最近记录: |