我是 Python 的新手,正在尝试执行嵌套循环。我有一个非常大的文件(110 万行),我想用它来创建一个包含每一行以及接下来的 N 行的文件,例如接下来的 3 行:
1 2
1 3
1 4
2 3
2 4
2 5
现在我只是想让循环使用行号而不是字符串,因为它更容易可视化。我想出了这段代码,但它的表现并不如我所愿:
with open('C:/working_file.txt', mode='r', encoding = 'utf8') as f:
for i, line in enumerate(f):
line_a = i
lower_bound = i + 1
upper_bound = i + 4
with open('C:/working_file.txt', mode='r', encoding = 'utf8') as g:
for j, line in enumerate(g):
while j >= lower_bound and j <= upper_bound:
line_b = j
j = j+1
print(line_a, line_b)
它给了我这个,而不是我想要的输出:
990 991
990 992
990 993
990 994
990 992
990 993
990 994
990 993
990 994
990 994
如您所见,内层循环为外层循环中的每一行迭代多次。似乎在外循环中每行应该只有一次迭代。我错过了什么?
编辑:我的问题在下面得到了回答,这是我最终使用的确切代码:
from collections import deque
from itertools import cycle
log = open('C:/example.txt', mode='w', encoding = 'utf8')
try:
xrange
except NameError: # python3
xrange = range
def pack(d):
tup = tuple(d)
return zip(cycle(tup[0:1]), tup[1:])
def window(seq, n=2):
it = iter(seq)
d = deque((next(it, None) for _ in range(n)), maxlen=n)
yield pack(d)
for e in it:
d.append(e)
yield pack(d)
for l in window(open('c:/working_file.txt', mode='r', encoding='utf8'),100):
for a, b in l:
print(a.strip() + '\t' + b.strip(), file=log)
最佳答案
基于 old docs 中的窗口示例你可以使用类似的东西:
from collections import deque
from itertools import cycle
try:
xrange
except NameError: # python3
xrange = range
def pack(d):
tup = tuple(d)
return zip(cycle(tup[0:1]), tup[1:])
def window(seq, n=2):
it = iter(seq)
d = deque((next(it, None) for _ in xrange(n)), maxlen=n)
yield pack(d)
for e in it:
d.append(e)
yield pack(d)
演示:
>>> for l in window([1,2,3,4,5], 4):
... for l1, l2 in l:
... print l1, l2
...
1 2
1 3
1 4
2 3
2 4
2 5
所以,基本上您可以将文件传递给窗口以获得所需的结果:
window(open('C:/working_file.txt', mode='r', encoding='utf8'), 4)
关于Python 嵌套循环 - 获取下 N 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20483453/