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

2024-04-25 22:06:49 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

results = []

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

    results.append([index, result_of_calculations])

但是,最近我的计算时间太长,所以我开始使用^{}来并行化我的循环。然而,现在我无法用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*]] 

Tags: of对象loopoutputindexobjectsparallel时间
1条回答
网友
1楼 · 发布于 2024-04-25 22:06:49

即使joblib不一定明确支持这个特性,我还是找到了一个更好的(更具Pythonic)方法(二战对this问题的评论):将list_of_objects转换成这样的子列表

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

并将new_list引入joblib函数,在该函数中,每个对象的索引都将显式附加。你知道吗

相关问题 更多 >