快速迭代三个字典?

2024-03-28 22:45:49 发布

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

我处理的是三本非常大的字典,看起来像这样:

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)

这是真正没有效率和优化的方式来完成这项任务。我想用熊猫。你知道吗

如何在最小的时间复杂度下完成这项任务?你知道吗

谢谢你!你知道吗


Tags: nameinforif字典value方式items
3条回答

因为这些是字典,所以您只需要迭代一个。您可以使用该键从其他键获取相应的值。你知道吗

示例:

for key, value in dict_a.items():
        final_dict['name'].append(key)
        final_dict['first_value'].append(value)
        final_dict['second_value'].append(dict_b[key])
        final_dict['third_value'].append(dict_c[key])

怎么样:

pd.DataFrame({i:d for i,d in enumerate([dict_a,dict_b,dict_c])} )

输出:

                   0                1                2
a b  [0.2, 0.3, 0.9]  [0.1, 0.5, 0.3]  [0.1, 0.5, 0.3]
t e  [0.5, 0.1, 0.6]  [0.6, 0.1, 0.6]  [0.6, 0.5, 0.6]

试试这个方式:-你知道吗

df = pd.DataFrame([dict_a, dict_b, dict_c], index = ['first_value', 
'second_value', 'third_value']).T
df['names'] = df.index
df.index = [0, 1]
print(df)

你知道吗输出:-你知道吗

       first_value     second_value      third_value   names
0  [0.2, 0.3, 0.9]  [0.1, 0.5, 0.3]  [0.1, 0.5, 0.3]  (a, b)
1  [0.5, 0.1, 0.6]  [0.6, 0.1, 0.6]  [0.6, 0.5, 0.6]  (t, e)

相关问题 更多 >