使用多处理将元素添加到列表 python

Add element to list using multiprocessing python

我定义了一个接受单个整数输入并将 return 输出整数的函数。

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。我知道如何使用顺序方式实现此目的,但我想知道如何并行化此任务。 提前致谢。

首先将输出附加到 'input_list'。

output_list = numpy.zeros_like(input_list)
output_list += input_list

这里进行数组编程。

你需要的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]