基于字典值的排序列表 [英] Sorting list based on the values of dictionary

查看:72
本文介绍了基于字典值的排序列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字典y = {6:34,5:40,3:70,2:80}和列表m = [5,2,3],其中仅包含字典y的某些键.我必须根据字典y = {2:80,3:70,5:40,6:34}的值进行排序,并且仅考虑列表m中存在的键,并且最终结果应该已经对m =[2,3,5]

I have a dict y = {6:34,5:40,3:70,2:80} and list m = [5,2,3] which has only some keys of dict y. I have to sort based on values of dict y = {2:80,3:70,5:40,6:34} and only consider keys present in list m and final result should have sorted m =[2,3,5]

推荐答案

您可以将sorted()与按键功能一起使用,该按键功能将根据字典值对列表进行排序:

You can use sorted() with a key function which will sort your list based on your dictionary values:

>>> sorted(m, key= lambda x: -y.get(x))
[2, 3, 5]

请注意,由于sorted()以升序模式对项目进行排序,因此您可以使用dict值的负值来使其对列表进行降序排序.或者,您可以将reverse参数更改为True:

Note that since sorted() sorts the items in ascending mode you can use negative value of the dict values to make it sort your list descending. Or you could change the reverse argument to True:

>>> sorted(m, key= lambda x: y.get(x), reverse=True)
[2, 3, 5]

这篇关于基于字典值的排序列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆