0

辞書をスコアで並べ替えたい。スコアが同じ場合は、名前で並べ替えます

{ 
'sudha'  : {score : 75} 
'Amruta' : {score : 95} 
'Ramesh' : {score : 56} 
'Shashi' : {score : 78} 
'Manoj'  : {score : 69} 
'Resham'  : {score : 95} 
} 

助けてくださいありがとう。

4

2 に答える 2

6

私はこれがうまくいくはずだと思う...

sorted(yourdict,key=lambda x:(yourdict[x]['score'],x))

タプル(スコア、名前)を比較することで機能します。タプルの比較では、最初の項目が調べられます。それらが同じ場合は、2 番目の項目が調べられます。したがって、(55,'jack') > (54,'lemon) および (55,'j') < (55,'k') です。

もちろん、これはyourdict目的の順序で のキーを返します。辞書には順序の概念がないため、辞書を実際にソートする方法はありません。

于 2012-05-23T13:36:36.040 に答える
4
d = { 
'sudha'  : {'score' : 75},
'Amruta' : {'score' : 95},
'Ramesh' : {'score' : 56}, 
'Shashi' : {'score' : 78}, 
'Manoj'  : {'score' : 69}, 
'Resham'  : {'score' : 95}, 
} 

sorted(d, key=lambda x: (d[x]['score'], x))

戻り値:

['Ramesh', 'Manoj', 'sudha', 'Shashi', 'Amruta', 'Resham']
于 2012-05-23T13:36:47.493 に答える