Python 嵌套循环 - 获取下 N 行

标签 python loops nested

我是 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/

相关文章:

python - 在 python 中按特定顺序对元素进行排序

python - Discord.py 按钮和下拉菜单,未获取正确的库

python - 如何使用请求发送带有 header 的 PATCH 请求

php - 简单的for循环不起作用

nested - Pyspark - 使用 collect_list 时保留空值

python - Pandas read_xml 将 "N/A"读取为 NaN

c# - 嵌套 while 循环替代方案

ios - 在 swift 中找到第一个正元素后退出循环

java - 在 Java 中定义嵌套类/对象/枚举结构的最佳方法是什么?

javascript - 如何将嵌套的对象数组推送到数组?