如何在python中打印列表理解的进度? [英] How to print the progress of a list comprehension in python?
本文介绍了如何在python中打印列表理解的进度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的方法中,我必须返回列表中的列表.我想要一个列表理解功能,因为它的性能很高,因为创建列表大约需要5分钟.
In my method i have to return a list within a list. I would like to have a list comprehension, because of the performance since the list takes about 5 minutes to create.
[[token.text for token in document] for document in doc_collection]
是否可以打印进度,当前创建过程位于哪个文档中?像这样的东西:
Is there a possibility to print out the progress, in which document the create-process currently are? Something like that:
[[token.text for token in document]
and print(progress) for progress, document in enumerate(doc_collection)]
感谢您的帮助!
推荐答案
1:使用辅助功能
def report(index):
if index % 1000 == 0:
print(index)
def process(token, index, report=None):
if report:
report(index)
return token['text']
l1 = [{'text': k} for k in range(5000)]
l2 = [process(token, i, report) for i, token in enumerate(l1)]
2:使用and
和or
语句
2: Use and
and or
statements
def process(token):
return token['text']
l1 = [{'text': k} for k in range(5000)]
l2 = [(i % 1000 == 0 and print(i)) or process(token) for i, token in enumerate(l1)]
3:同时使用
def process(token):
return token['text']
def report(i):
i % 1000 == 0 and print(i)
l1 = [{'text': k} for k in range(5000)]
l2 = [report(i) or process(token) for i, token in enumerate(l1)]
所有3种方法均可打印:
All 3 methods print:
0
1000
2000
3000
4000
2的工作方式
-
i % 1000 == 0 and print(i)
:and
仅在第二条语句为True
时检查第二条语句,因此仅在i % 1000 == 0
时打印
-
or process(token)
:or
始终检查两个语句,但返回评估为True
的第一个语句.- 如果为
i % 1000 != 0
,则第一个语句为False
,并且将process(token)
添加到列表中. - 否则,第一个语句为
None
(因为print
返回None
),同样,or
语句将process(token)
添加到列表中
i % 1000 == 0 and print(i)
:and
only checks the second statement if the first one isTrue
so only prints wheni % 1000 == 0
or process(token)
:or
always checks both statements, but returns the first one which evals toTrue
.- If
i % 1000 != 0
then the first statement isFalse
andprocess(token)
is added to the list. - Else, then the first statement is
None
(becauseprint
returnsNone
) and likewise, theor
statement addsprocess(token)
to the list
3种工作原理
与2相似,因为
report(i)
没有任何return
内容,因此它等效于None
,并且or
将process(token)
添加到列表中Similarly as 2, because
report(i)
does notreturn
anything, it evals toNone
andor
addsprocess(token)
to the list这篇关于如何在python中打印列表理解的进度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- If
- 如果为
查看全文