【问题标题】:Python sort a dict by values, producing a list, how to sort this from largest to smallest?Python按值对dict进行排序,生成一个列表,如何从最大到最小排序?
【发布时间】:2014-04-26 13:49:37
【问题描述】:

我现在已经阅读了一些关于如何在 python 中对 dict 进行排序的帖子,问题是我找到的解决方案没有按正确的顺序对 dict 进行排序。我发现的是这个

results = sorted(results.items(), key=lambda x: x[1])

这会产生一个从最小到最大排序的键值对列表,我想从最大到最小。这里有什么简单的解决方法吗?

【问题讨论】:

    标签: python sorting dictionary


    【解决方案1】:

    反转列表:

    results = sorted(results.items(), key=lambda x: x[1])
    results.reverse()
    

    甚至更好:

    results = sorted(results.items(), key=lambda x: x[1], reverse=True)
    

    或最好的:

    results = sorted(results.items(), cmp=lambda a,b: b[1]-a[1])
    

    虽然奇怪的是第一个选项是最快的:

    In [48]: %timeit sorted(x.items(), key=lambda x: x[1]).reverse()
    100000 loops, best of 3: 2.93 us per loop
    
    In [49]: %timeit sorted(x.items(), key=lambda x: x[1], reverse=True)
    100000 loops, best of 3: 3.24 us per loop
    
    In [50]: %timeit sorted(x.items(), cmp=lambda a,b: b[1]-a[1])
    100000 loops, best of 3: 3.11 us per loop
    

    【讨论】:

    • 有道理...谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-15
    • 2018-03-08
    • 2019-03-17
    • 1970-01-01
    相关资源
    最近更新 更多