【问题标题】:How to sort multiple digit dictionary values from highest to lowest如何将多个数字字典值从最高到最低排序
【发布时间】:2016-05-15 18:32:13
【问题描述】:

有没有办法对多位数的字典值进行排序?我已经尝试过这里使用的方法:How to sort a dictionary to print from highest value to lowest for each key?,但它只适用于单个数字的整数值。例如,我的代码目前如下所示:

for line in students:
        student = line.split(' ')
        d[student[1]] = (student[3])
        print (d)
     od = sorted(d.items(), key=lambda x: x[1], reverse=True)
     print(od)

students 是这个文本文件的 .readlines() 结果,我使用的是第一个分数:

Name= kirsty Score= 9 10 10 `
Name= anne Score= 4 5 6  
Name= charlie Score= 1 1 1 
Name= bruce Score= 7 8 9 
Name= danny Score= 10 11 12 

Danny 应该是字典中的第一个条目,但我的实际输出是这样的:

[('kirsty', '9'), ('bruce', '7'), ('anne', '4'), ('danny', '10'), ('charlie', '1')]

有人可以帮忙吗?

【问题讨论】:

  • 试试lambda x: int(x[1])作为排序键!

标签: python sorting dictionary


【解决方案1】:

您需要转换为ints 进行比较。您看到的行为来自比较字符串。

例如-

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

【讨论】:

  • 谢谢!这正是我所需要的——对不起,我回答得太晚了!
【解决方案2】:

更改您的键函数以将计算排序的值转换为数字。假设您只使用整数,排序行将是:

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

【讨论】:

    猜你喜欢
    • 2018-12-21
    • 2019-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-20
    • 2016-09-19
    • 1970-01-01
    • 2019-05-29
    相关资源
    最近更新 更多