首页 > 解决方案 > 在 for 循环中使用多处理?

问题描述

我有以下 for 循环,它需要 2 个数组,将第一列中的元素值与第二列中的元素模糊匹配,并返回最接近的匹配项。因为我正在使用的数据集非常庞大,所以循环需要永远运行。有没有办法让我使用多处理来提高循环的速度?

    def match(Col1,Col2):
    overall=[]
    for n in Col1:
        result=[(fuzz.token_set_ratio(n, n2),n2) 
                for n2 in Col2 if fuzz.token_set_ratio(n, n2)>20
               ]
        if len(result):
            result.sort()
            #print("CP4")
            #print('result {}'.format(result))
            print("Best Match={}".format(result[-1][1]))
            overall.append(result[-1][1])
        else:
            overall.append(" ")
    return overall ```

标签: pythonpython-3.xpandasmultiprocessing

解决方案


multiprocessing.Pool似乎适合您的用例。如果您希望不同的工人处理不同的元素Col1

def work(n):
    result = []
    for n2 in Col2:
        token_set_ratio = fuzz.token_set_ratio(n, n2)
        if token_set_ratio > 20:
            result.append(token_set_ratio)
    if result:
        best_match = max(result)
        print("Best Match={}".format(best_match))
        return best_match
    else:
        return ' '

num_workers = 8
with multiprocessing.Pool(num_workers) as pool:
    overall = pool.map(work, Col1)

请注意,我还包括两个性能优化:

  1. 只计算fuzz.token_set_ratio(n, n2)一次并重复使用结果;
  2. 取列表的最大值result而不是对其进行排序,因为您只需要最佳匹配。这将复杂性从 O(n log(n)) 提高到 O(n)。

推荐阅读