简体   繁体   English

Python3,懒惰的打印

[英]Python3, a lazy print

for my last project in Python3, i used a custom lazy generator to generate my data. 对于我在Python3中的最后一个项目,我使用了一个自定义的惰性生成器来生成数据。 Then use imap from a Pool (multiprocessing). 然后从池中使用imap (多处理)。 So at this point, not any computation have been made. 因此,到目前为止,尚未进行任何计算。 The next step is to output the computed data on a file. 下一步是将计算的数据输出到文件中。 To do so, I either print(list(data)) or print(*data) which causes the computation of the whole data (approx 1.5Gib right now, bit will grow fast), either do a for loop and print each piece of data, which do a lot of call to print (approx 10e6 calls right now, but will grow fast). 为此,我要么print(list(data))要么print(*data)导致整个数据的计算(现在大约为1.5Gib,位会快速增长),或者进行for循环并打印每条数据,这需要进行大量打印工作(目前大约有10e6个调用,但会很快增长)。

So, is there a way to make print iterate over a lazy generator? 因此,有没有办法使print在惰性发生器上进行迭代?

Thank you. 谢谢。

Using this recipe from the itertools docs: 使用itertools文档中的此配方:

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 izip_longest(fillvalue=fillvalue, *args)

You can batch the calls to print yourself: 您可以批量调用以print自己:

for batch in grouper(data, 1000, ''):
    print('\n'.join(batch))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM