我有一个问题与我的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))
多谢
您可以使用标准库中的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)
可以在整数除法上使用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)