【发布时间】:2019-12-03 20:01:38
【问题描述】:
我正在处理非常大的三个字典,如下所示:
dict_a = { ( 't','e' ) : [0.5,0.1,0.6], ( 'a','b' ) : [0.2,0.3,0.9] }
dict_b = { ( 'a','b' ) : [0.1,0.5,0.3] , ( 't','e' ) : [0.6,0.1,0.6] }
dict_c = { ( 'a','b' ) : [0.1,0.5,0.3] , ( 't','e' ) : [0.6,0.5,0.6] }
我正在寻找这样的输出:
name first_value second_value third_value
0 (t, e) [0.5, 0.1, 0.6] [0.6, 0.1, 0.6] [0.6, 0.5, 0.6]
1 (a, b) [0.2, 0.3, 0.9] [0.1, 0.5, 0.3] [0.1, 0.5, 0.3]
我试过的是:
final_dict = {'name': [] , 'first_value' : [] ,'second_value': [] , 'third_value': [] }
for a,b in dict_a.items():
for c,d in dict_b.items():
for e,f in dict_c.items():
if a==c==e:
final_dict['name'].append(a)
final_dict['first_value'].append(b)
final_dict['second_value'].append(d)
final_dict['third_value'].append(f)
这确实不是高效和优化的方式来完成这项任务。我正在考虑使用熊猫。
如何以最小的时间复杂度完成这项任务?
谢谢!
【问题讨论】:
-
这会从所有字典中获取所有键,因此您只需要一个循环。 O(n) + O(n) = O(n) stackoverflow.com/questions/5242311/…
标签: python python-3.x pandas loops dictionary