【发布时间】:2013-12-27 07:40:18
【问题描述】:
我是 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)
【问题讨论】:
-
for j, line in enumerate(g)和j = j+1永远不应该在一起...... -
我看不出它还能如何工作 - 你在一个循环中有一个循环。当然,line_a 通过文件
g进行的所有迭代都保持不变。 -
@sashkello 为什么不应该这样做?什么是替代方案?我刚开始学习python。
-
for i in mylist遍历mylist中的所有对象。同时修改i会使程序混乱,因为i不一定在列表中。在你的情况下,你可以做for n in range(lower_bound, upper_bound+1)。