首页 > 解决方案 > 使用多处理python将元素添加到列表

问题描述

我已经定义了一个接受单个整数输入并返回输出整数的函数。

def get_output(n):
  output = # process the integer
  return output

现在我已经定义了一个必须使用上面定义的函数处理的输入列表。

input_list = [1,2,3,5,6,8,5,5,8,6,5,2,5,2,5,4,5,2]

现在我已经定义了一个空的输出列表,它将存储函数的输出。

output_list = []

现在我想浏览每一项input_list并将其附加到output_list. 我知道如何使用顺序方式来实现这一点,但我想知道如何并行化这个任务。提前致谢。

标签: pythonmultithreadingconcurrencymultiprocessing

解决方案


IIUC 你需要:

如果您的整数进程更多的 IO 绑定,线程可能会更好地工作。

线程的 IO 密集度更高,因此,如果您需要这样做,您可以尝试:

from concurrent.futures import ThreadPoolExecutor
def get_output(n):
    output = n ** 2
    return output

input_list = [1,2,3,5,6,8,5,5,8,6,5,2,5,2,5,4,5,2]
output_list = []

if __name__ == '__main__':
    with ThreadPoolExecutor(max_workers=6) as pool:
        output_list.extend(pool.map(get_output, input_list))
        
print(output_list)

这会处理列表并对所有元素求平方,并将其并行应用于每 6 个元素,如您所见,我指定了max_workers=6.

如果您的整数进程更受 CPU 限制,请使用多处理。

使用几乎相同的代码:

from concurrent.futures import ProcessPoolExecutor
def get_output(n):
    output = n ** 2
    return output

input_list = [1,2,3,5,6,8,5,5,8,6,5,2,5,2,5,4,5,2]
output_list = []

if __name__ == '__main__':
    with ProcessPoolExecutor(max_workers=6) as pool:
        output_list.extend(pool.map(get_output, input_list))
        
print(output_list)

这也是一样的,它对每 6 个元素并行处理和平方所有元素。

两个代码输出:

[1, 4, 9, 25, 36, 64, 25, 25, 64, 36, 25, 4, 25, 4, 25, 16, 25, 4]

推荐阅读