我想一次读4或6行。我希望你们能帮我解决这个问题。
with open('readme.txt') as f:
list_of_4tuples = [ (line,f.readline()) for line in f ]
for (line1,line2,line3,line4) in list_of_4tuples: # Work with them in pairs.
print(f'a: {line1}{line2}{line3}{line4}')
(1、2、3、4),那么(2、3、4、5)
with open('readme.txt') as f:
lines = f.read().splitlines()
for (line1, line2, line3, line4) in zip(lines, lines[1:], lines[2:], lines[3:]): # Work with them in pairs.
print(f'a: {line1}{line2}{line3}{line4}')
如果你没有,行是重复的。
(1,2,3,4) then (5,6,7,8)
with open('readme.txt') as f:
for (line1, line2, line3, line4) in zip(f, f, f, f):
print(f'a: {line1}{line2}{line3}{line4}')
您可以创建四个迭代器,它们以不同的偏移量同时遍历行。
with open('readme.txt') as f:
lines = f.readlines()
iterators = [iter(lines) for _ in range(4)]
for k in range(1, 4):
for j in range(4-k, 4):
next(iterators[j]) # advance the iterators
for line1, line2, line3, line4 in zip(*iterators):
...