【问题标题】:Sorting a dictionary by REVERSE VALUE then NON-REVERSE KEY按 REVERSE VALUE 然后 NON-REVERSE KEY 对字典进行排序
【发布时间】:2016-10-04 21:48:33
【问题描述】:

我有一个字典,其中包含要排序的字符串键和 int 值。我希望它首先按数值递减排序,然后按字母顺序。

例如,如果您的字典包含:

my_dict = {'zebra':1, 'the':201, 'apple':1, 'chicken':58}

生成的排序列表将包含:

{('the', 201), ('chicken', 58), ('apple', 1), ('zebra', 1)

目前我正在使用以下内容:

my_list = sorted(my_dict.items(), key=lambda x: (x[1],x[0])

我得到一个列表,首先按升序排列,然后按字母顺序排列。

如何反转值而不是键?我知道您可以将第三个参数 reverse=[boolean] 传递给 sorted() 方法,但它要么反转要么不反转键和值。怎么能只按一次反转排序?感谢您的帮助!

【问题讨论】:

  • 不是真正重复,但“按值降序排序,然后按键升序排序”已发布on this question

标签: python sorting dictionary


【解决方案1】:

只需否定该值并将其用作主键:

>>> my_dict = {'zebra':1, 'the':201, 'apple':1, 'chicken':58}
>>> sorted(my_dict.items(), key=lambda x: (-x[1], x[0]))
[('the', 201), ('chicken', 58), ('apple', 1), ('zebra', 1)]

【讨论】:

  • 比我的简单;我喜欢! :)
【解决方案2】:

由于 Python 中的排序是稳定的,您可以简单地对它进行两次排序:首先按辅助键,然后按主键:

In [29]: from operator import itemgetter
In [30]: my_dict = {'zebra':1, 'the':201, 'apple':1, 'chicken':58}
In [31]: my_list = sorted(sorted(my_dict.iteritems(), key=itemgetter(0)), key=itemgetter(1), reverse=True)

In [32]: my_list
Out[32]: [('the', 201), ('chicken', 58), ('apple', 1), ('zebra', 1)]

This documentation 更详细地解释了 Python 中的稳定排序。

【讨论】:

    猜你喜欢
    • 2013-01-06
    • 1970-01-01
    • 1970-01-01
    • 2013-08-29
    • 2012-04-12
    • 1970-01-01
    相关资源
    最近更新 更多