Python嵌套循环 – 接下来的N行
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Python嵌套循环 – 接下来的N行,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2016字,纯文字阅读大概需要3分钟。
内容图文
![Python嵌套循环 – 接下来的N行](/upload/InfoBanner/zyjiaocheng/817/26cd8641104c4b30b7b181affea5bdde.jpg)
我是Python的新手,并试图做一个嵌套循环.我有一个非常大的文件(110万行),我想用它来创建一个文件,每行包含接下来的N行,例如接下来的3行:
1 2
1 3
1 4
2 3
2 4
2 5
现在我只是试图让循环使用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)
它不是我想要的输出,而是给我这个:
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行全部内容,希望文章能够帮你解决Python嵌套循环 – 接下来的N行所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。