gpt4 book ai didi

python - 跟踪 Joblib 中并行 for 循环的索引

转载 作者:太空宇宙 更新时间:2023-11-03 20:34:28 28 4
gpt4 key购买 nike

在Python中,我有一个需要在循环中迭代的对象列表,并为每次迭代输出一个结果,同时还跟踪正在迭代的对象的索引.

通常情况下,这不是问题,因为我可以使用 enumerate 并执行

results = []

for index, value in enumerate(list_of_objects):
... *calculations* ...

results.append([index, result_of_calculations])

但是,最近我的计算时间太长,所以我开始使用 joblib并行化我的循环。但是,现在我无法跟踪使用 enumerate 的操作索引,因为循环的每个部分都可以在不规则的时间开始和结束,我被难住了。

我怎样才能让像下面这样的代码工作,其中子数组的每个第一个值引用用于该特定迭代的对象的索引?

from joblib import Parallel, delayed

def single_loop_function(x):
single_output = *some calculations based on x*
return single_output

all_output = Parallel(n_jobs=-1, verbose=3, backend="loky")(
map(delayed(single_loop_function), list_of_objects))

print(all_output)
[[0, *result*], [1, *result*], ... [5, *result*], [3, *result*]]

最佳答案

即使joblib不一定明确支持此功能,我也找到了一种更好(更Pythonic)的方法(wwii对this问题的评论):转换list_of_objects 到这样的子列表列表,

new_list = [[i, value] for i, value in enumerate(list_of_objects)]

并将 new_list 提供给 joblib 函数,其中每个对象的索引将显式附加。

关于python - 跟踪 Joblib 中并行 for 循环的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57260042/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com