首页 > 解决方案 > 如何在 Python 中使用多处理进行列表减法

问题描述

我正在使用以下代码进行列表减法。

X = [1,2,3,4,5,6]
Y = [4,5]

# to find the elements which in X but not in Y
result = [e for e in X if e not in Y]
# expected result: [1,2,3,6]

由于 X 和 Y 中有数百万个元素,

减法运算很慢,

单个 CPU 使用率达到 100%(剩下其他 10+ 个 CPU 使用率 0%),也许使用多处理可能会改善这种情况。

如何在 Python 中使用多处理来做到这一点?

from multiprocessing import Pool
????
pool = Pool(11)
pool.map(?, ?)
pool.close()
pool.join()

标签: pythonmultiprocessing

解决方案


您可能想阅读有关e in X. 如果 X 是一个列表,O(n)如果将它用于所有项目,则需要时间,这真的很慢。与即时检查集合的项目不同。为了进一步优化,我会使用numpy,因为它的循环速度更快。

Z = set(Y)
result = [e for e in X if e not in Z]

推荐阅读