2014-08-31 59 views
2

比方說,我有一個像一本字典:然後按字母順序重點Python3排序字典的價值

h=[('a',5), ('f', 3), ('b',3), ('c',3), ('d',1), ('e',4) ] 

我需要它有序,如:

[('a',5), ('e',4), ('b',3), ('c',3), ('f',3), ('d',1)] 

我可以用一些與Python 2解決這個像這樣:

sortedList= sorted(h.iteritems(),key=lambda(k,v):(-v,k)) 

我可以在Python 3中使用類似這樣的東西:

import operator 
sortedList =sorted(h.items(), key=operator.itemgetter(1,0) , reverse=True) 

但它出來像這樣

[('a',5), ('e',4), ('f',3), ('c',3), ('b',3), ('d',1)] 

我如何能逆轉決勝局操作?

+2

在PY3不允許的唯一的事情是,在lambda中解包。 'lambda x:(-x [1],x [0])'適用於兩個版本。 – roippi 2014-08-31 22:51:57

+0

Python的排序是穩定的 - 所以你可以只排序兩次 – 2014-08-31 22:54:43

+0

h是一個列表,所以你不能在python 3中使用h.items() – 2014-08-31 23:00:40

回答

1

您可以在Python 3使用這個調用來排序的功能:

sortedList = sorted(h, key=lambda k: (-k[1], k[0])) 

這將給予同樣的結果蟒蛇2排序:

[('a',5), ('e',4), ('b',3), ('c',3), ('f',3), ('d',1)]