python - 如何偶尔为长时间运行的 Python 列表理解提供反馈

标签 python list list-comprehension

如果您在 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/

相关文章:

python - 扩展列表理解选项 - Python

python - 我不希望 psycopg2 在查询结果中转义换行符 (\n)

Python 结构大小不匹配

python - 我如何检查 python 中的 keyhold

Java 相当于 python 的 getattr?

java - 比较器类显示错误排序

c++ - std::shuffle 不能用 std::list 编译

python - 列表理解与迭代

python - 为什么在 lambda 函数中将字符串转换为整数比使用列表理解进行转换要慢

list - 如何在没有 GADT 或数据类型上下文的情况下定义 List 的 Eq 实例