ras*_*oor 5 python loops nested
我是Python的新手,并试图做一个嵌套循环.我有一个非常大的文件(110万行),我想用它来创建一个文件,每行包含接下来的N行,例如接下来的3行:
1 2
1 3
1 4
2 3
2 4
2 5
Run Code Online (Sandbox Code Playgroud)
现在我只是试图让循环使用rownumbers而不是字符串,因为它更容易可视化.我想出了这个代码,但它的表现并不像我想要的那样:
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)
Run Code Online (Sandbox Code Playgroud)
它不是我想要的输出,而是给我这个:
990 991
990 992
990 993
990 994
990 992
990 993
990 994
990 993
990 994
990 994
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,内循环对外循环中的每一行迭代多次.看起来外循环中每行只应该有一次迭代.我错过了什么?
编辑:我的问题在下面得到解答,这是我最终使用的确切代码:
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)
Run Code Online (Sandbox Code Playgroud)
基于旧文档的窗口示例,您可以使用以下内容:
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)
Run Code Online (Sandbox Code Playgroud)
演示:
>>> 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
Run Code Online (Sandbox Code Playgroud)
所以,基本上你可以将文件传递给窗口以获得所需的结果:
window(open('C:/working_file.txt', mode='r', encoding='utf8'), 4)
Run Code Online (Sandbox Code Playgroud)