Python:如何将比较两个列表的作业并行化?
我有两个列表,需要逐个元素进行比较和计算。随着这些列表越来越大,性能也越来越差。有人建议将其中一个列表分成N个部分,并并行运行比较。如何并行运行这些Python:如何将比较两个列表的作业并行化?,python,pandas,parallel-processing,Python,Pandas,Parallel Processing,我有两个列表,需要逐个元素进行比较和计算。随着这些列表越来越大,性能也越来越差。有人建议将其中一个列表分成N个部分,并并行运行比较。如何并行运行这些 key={} #compare each list, element by element for i in range(len(list1)): for j in range(len(list2)): matched = False try: matched = match_func
key={}
#compare each list, element by element
for i in range(len(list1)):
for j in range(len(list2)):
matched = False
try:
matched = match_function(list[i]['typeforma'], list[i]['typeformb'],list[j]['typeforma'], list[j]['typeformb'], )
except:
print("Error",i,j)
if matched:
# store two matches in the dictionary
key[list2[j]['id']]=list1[i]['identifier']
break;
j+=1
i+=1
假设您确实需要将笛卡尔积(列表1中的每个元素与列表2中的每个元素进行比较,而不仅仅是将列表1中的每个元素与列表2中的相应元素进行比较),最简单的方法是用对a或a的
map
调用替换外部循环
唯一的诀窍是,你不想尝试共享这个可变的键
dict;相反,传回单独的dict并在末尾合并
例如:
def compare_to_list2(i):
key = {}
for j in range(len(list2)):
matched = False
try:
matched = match_function(list[i]['typeforma'], list[i]['typeformb'],list[j]['typeforma'], list[j]['typeformb'], )
except:
print("Error",i,j)
if matched:
# store two matches in the dictionary
key[list2[j]['id']]=list1[i]['identifier']
break;
j+=1
return key
with concurrent.futures.ProcessPoolExecutor as x:
key = {}
for result in x.map(compare_to_list2, range(len(list1)), chunksize=1024):
key.update(result)
尝试使用
chunksize
,但首先,有一些方法可以改进这一点。仅举一个例子,您实际上应该直接在list1
和list2
上进行迭代,而不是在range(len(list1))
和range(len(list2))
上进行迭代,这样做不仅会使事情更简单,而且会更高效,尤其是在块大小较大的情况下。事实上,通常最好先简化,然后优化。提供有关列表的更多信息。他们有相同的镜头吗?里面有什么?您能提供示例输入和预期输出吗?当然,性能会受到影响,您使用的是n^2算法。解决这个问题,而不是尝试运行多个线程。@MarkRansom我认为他是故意做产品,而不是拉链。