【问题标题】:Sorting a dict by value in descending order of utf-8按 utf-8 的降序按值对 dict 进行排序
【发布时间】:2020-03-16 03:49:48
【问题描述】:

我有一本这样的字典:{'ex1': 3, 'ex2': 4, 'ex3': 3},我想按值对其进行排序。所以我这样做:results = sorted(results.items(), key=lambda x: x[1], reverse=True)。我输入了reverse=True,因为我希望它按降序排序。
所以代码是这样的:

results  = {'ex1': 3, 'ex2': 4, 'ex3': 3}
results = sorted(results.items(), key=lambda x: x[1], reverse=True)
for item in results:
    print (item[0])

输出是:

ex2
ex1
ex3

但我想要的输出应该是这样的:

ex2
ex3
ex1

因为在 utf-8 中,ex3 大于 ex1。
其实我想说的是,当两个键的值是偶数时,我想按降序打印它们。
我究竟做错了什么? 提前感谢您的回答

【问题讨论】:

  • 你告诉它只对数字进行排序,而不考虑其他任何东西

标签: python python-3.x string sorting dictionary


【解决方案1】:

这应该可行 - 键函数可以返回一个元组:

results  = {'ex1': 3, 'ex2': 4, 'ex3': 3}
results = sorted(results.items(), key=lambda x: (x[1],x[0]), reverse=True)
for item in results:
    print (item[0])

给出输出:

ex2
ex3
ex1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-09
    • 2016-03-10
    • 1970-01-01
    • 1970-01-01
    • 2013-02-21
    • 1970-01-01
    • 2011-03-25
    相关资源
    最近更新 更多