迭代.txt中的行并循环每个“15行”

时间:2016-07-03 17:25:15

标签: python list stream rows

我的python脚本有问题。我找不到一种方法只对前15行进行计算,然后仅为第二行15行,然后仅为第三行15行...这些行来自txt文件。

with open('/Users/sammtt/data/test2.txt','r') as f:
for line in nonblank_lines(f):
    print(my_txt(line,0))
    print(my_txt(line,2))

    print(my_txt(line,6))
    print(my_txt(line,8))

非常感谢

2 个答案:

答案 0 :(得分:2)

您可以将此recipe用于标准库中的itertools

from itertools import zip_longest

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)

将其应用于您的代码:

with open('/Users/sammtt/data/test2.txt','r') as f:
    for chunk in grouper(nonblank_lines(f), 15):
        process_chunk(chunk)

答案 1 :(得分:0)

您可以对整数除法使用itertools.groupby

>>> from itertools import groupby
>>> f = range(0, 100)
>>> for i, g in groupby(f, key=lambda x: x//15):
...     print(list(g))
...
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
[15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
[30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44]
[45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59]
[60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74]
[75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89]
[90, 91, 92, 93, 94, 95, 96, 97, 98, 99]

对于您的文件对象,您可以使用enumerate逐行说明:

with open('/Users/sammtt/data/test2.txt','r') as f:
    for i, group_of_15 in groupby(enumerate(nonblank_lines(f)), key=lambda x: x[0]//15):
        chunk = list(map(lambda x: x[1], group_of_15))
        do_something(chunk)