python - 在 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 ```
解决方案
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)
请注意,我还包括两个性能优化:
- 只计算
fuzz.token_set_ratio(n, n2)
一次并重复使用结果; - 取列表的最大值
result
而不是对其进行排序,因为您只需要最佳匹配。这将复杂性从 O(n log(n)) 提高到 O(n)。
推荐阅读
- r - 使用 ggplotly 删除跟踪信息并控制鼠标悬停在瀑布图的信息上
- android-studio - 如何删除分号后的字符,因为我不能使用 split()
- javascript - TypeError:change.after.val 不是一个函数 firebase
- oop - 此代码中是否正确解释了可导航性?
- spring-boot - Kotlin 原语的 Spring 验证
- ruby-on-rails - 已解决 - Ruby On Rails 中 FactoryBot 构建方法中的 ArgumentError
- html - 聊天框 UI 不使用 react-bootstrap Accordion 滚动
- python - 在 django 中发送响应后更改上下文
- asp.net-web-api - ASP.Net Web API 没有时间返回 JSON 日期时间
- r - 为什么我不能绘制这个?