python - 使用多处理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
. 我知道如何使用顺序方式来实现这一点,但我想知道如何并行化这个任务。提前致谢。
解决方案
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]
推荐阅读
- c# - 'AsyncEnumerableReader' 在枚举值时达到了配置的最大缓冲区大小
- python - 尽管格式正确,熊猫仍无法推断时间序列频率?
- bash - 如何检查基于busybox的Unix系统中是否没有传递命令行参数?
- node.js - Nodemailer gmail ouath问题
- elm - 如何从 Elm 中的 Html.Attribute 中提取值
- android - 我如何从另一个活动的 firestore 中获取存储的数据
- sql - Snowflake SQL 从每日登录事件中查找每个用户每月登录事件
- ruby - RuboCop - 为我的整个 Rails 项目禁用样式/AndOr?
- marklogic-dhf - MarkLogic DataHub V5 如何限制自定义流中返回的行数
- reactjs - 每次切换时,Redux 复选框列表中的第二项都会发生变化