我需要以这样的方式读取文件的行,这将作为具有两个单元的移位寄存器.例如:
with open("filename", 'r') as file:
--first iteration--
present = line1
next = line2
do something
--second iteration--
present = line2
next = line3
do something
--third iteration--
present = line3
next = line 4
do someting
and so on....
Run Code Online (Sandbox Code Playgroud)
它可以完成,open(file, 'r')但不能保证文件将被关闭,因为脚本可能会因为在最后一次迭代之前"做某事"而停止.
有什么优雅的方式吗?
当然:
with open("filename", 'r') as file:
current_line = next(file) # Get 1st line, advance iterator to 2nd line
for next_line in file:
do_something(current_line, next_line)
current_line = next_line
Run Code Online (Sandbox Code Playgroud)
蒂姆的答案很好."发烧友"解决方案是使用文档中显示的pairwise配方:itertools.teeitertoos
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return zip(a, b)
Run Code Online (Sandbox Code Playgroud)
tee是一个非常整洁的功能.它可以在您想要多次迭代同一个迭代时使用.如果您或多或少地并行使用所有迭代器(而不是运行一次迭代完成,然后执行下一次迭代等),那么将整个迭代转储到一个list或其他容器中的空间效率会更高.可以一遍又一遍地迭代.
基本上,你传递一个可迭代对象,它返回一些独立的迭代器(默认情况下,两个).原始的iterable仅在处理返回迭代器之前最远的位置时才会提前.
这是一个tee带有生成器的演示,它在产生值之前打印一条消息:
>>> import itertools
>>> def gen():
for i in range(3):
print("gen yielding {}".format(i))
yield i
>>> a, b = itertools.tee(gen())
>>> next(a)
gen yielding 0
0
>>> next(a)
gen yielding 1
1
>>> next(b)
0
>>> next(b)
1
>>> next(b)
gen yielding 2
2
>>> next(b)
Traceback (most recent call last):
File "<pyshell#245>", line 1, in <module>
next(b)
StopIteration
>>> next(a)
2
>>> next(a)
Traceback (most recent call last):
File "<pyshell#247>", line 1, in <module>
next(a)
StopIteration
Run Code Online (Sandbox Code Playgroud)