如果您在 Python 中进行了长时间运行的列表理解,请说:
from itertools import combinations
print [w for w in (''.join(c) for c in combinations(words, 2)) if sorted(w) == letters]
其中words是200000个单词的列表,letters是字母的列表;有没有办法偶尔打印出到目前为止已处理的字数或其他形式的进度报告?
最佳答案
您需要将其转换为普通循环;不要尝试混合副作用函数:
from itertools import combinations
result = []
count = 0
for w in (''.join(c) for c in combinations(words, 2)):
if sorted(w) == letters:
result.append(w)
count += 1
if count % 2000 == 0:
print 'Progress: {0} matching combinations found'.format(count)
print result
或者,如果您想跟踪测试的组合,请将计数移到 if
之前:
from itertools import combinations
result = []
count = 0
for w in (''.join(c) for c in combinations(words, 2)):
count += 1
if count % 2000 == 0:
print 'Progress: {0} combinations scanned'.format(count)
if sorted(w) == letters:
result.append(w)
print result
关于python - 如何偶尔为长时间运行的 Python 列表理解提供反馈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14661229/