小编Bri*_*n D的帖子

按值对字典进行排序,然后按关键字按字母顺序排序 Python3

假设我有一本字典,如:

h=[('a',5), ('f', 3), ('b',3), ('c',3), ('d',1), ('e',4) ]
Run Code Online (Sandbox Code Playgroud)

我希望它排序如下:

[('a',5), ('e',4), ('b',3), ('c',3), ('f',3), ('d',1)]
Run Code Online (Sandbox Code Playgroud)

我可以用 Python 2 解决这个问题:

sortedList= sorted(h.iteritems(),key=lambda(k,v):(-v,k))
Run Code Online (Sandbox Code Playgroud)

我可以用这样的东西在 Python 3 中真正接近:

import operator
sortedList =sorted(h.items(), key=operator.itemgetter(1,0) , reverse=True)
Run Code Online (Sandbox Code Playgroud)

但结果是这样的

[('a',5), ('e',4), ('f',3), ('c',3), ('b',3),  ('d',1)]
Run Code Online (Sandbox Code Playgroud)

我怎样才能逆转决胜局的操作?

python sorting dictionary

4
推荐指数
1
解决办法
2702
查看次数

标签 统计

dictionary ×1

python ×1

sorting ×1