金狮镖局 Design By www.egabc.com
python中,我们可以对列表、字符串、元祖中的元素进行排序,那对于字典中的元素可以排序吗?其实对于字典本身我们无法进行排序,但是我们可以对字典按值排序。本文介绍python中对字典按照value进行排序的三种方法。
方法一:key使用lambda匿名函数取value进行排序
dict= {'a':1,'b':4,'c':2} sorted(dict.items(),key = lambda x:x[1],reverse = True)
方法二:使用operator的itemgetter进行排序
test_data_6=sorted(dict_data.items(),key=operator.itemgetter(1)) test_data_7=sorted(dict_data.items(),key=operator.itemgetter(1),reverse=True) print(test_data_6) #[(8, 2), (10, 5), (7, 6), (6, 9), (3, 11)] print(test_data_7) #[(3, 11), (6, 9), (7, 6), (10, 5), (8, 2)]
方法三:key和value分装成元祖,再进行排序
f = zip(d.keys(), d.values()) c = sorted(f) print(c)
字典按value排序内容扩展:
保存为字典后,按字典的value值大小排序,这个才是本题的难点,由于dict是无序的,所以只能用list去排序,把dict的key和value保存为tuplue对象
# 对字典按value排序 a = sorted(d.items(), key=lambda x: x[1], reverse=True) print(a)
参考代码:
# coding:utf-8 # 作者:上海-悠悠 a = ["a", "b", "a", "c", "a", "c", "b", "d", "e", "c", "a", "c"] # set集合去重 duixiang = set(a) # 先去重,取出计数对象 # 保存为dict,一一对应 d = {} for i in duixiang: d[i] = a.count(i) # 对字典按value排序 a = sorted(d.items(), key=lambda x: x[1], reverse=True) print(a)
金狮镖局 Design By www.egabc.com
金狮镖局
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
金狮镖局 Design By www.egabc.com
暂无python字典按照value排序方法的评论...
更新日志
2024年10月02日
2024年10月02日
- 纪钧瀚《钢琴阅读时光 雨中书店聆听轻音乐》[FLAC/分轨][399.62MB]
- 证声音乐图书馆《走向自然 疗心爵士乐》[320K/MP3][87.4MB]
- 证声音乐图书馆《走向自然 疗心爵士乐》[FLAC/分轨][184.94MB]
- 陈慧娴.2018-Priscilla-Ism演唱会3CD(2024环球红馆40复刻系列)【环球】【WAV+CUE】
- 郑秀文.1999-我应该得到(国)【华纳】【WAV+CUE】
- 陈家慧.2011-钢琴酒吧2CD【龙吟唱片】【WAV+CUE】
- 证声音乐图书馆《雨季 蓝调吉他 Rainy Blues》[320K/MP3][45.01MB]
- 证声音乐图书馆《雨季 蓝调吉他 Rainy Blues》[FLAC/分轨][109.13MB]
- 赞多《序章》[320K/MP3][45.54MB]
- 许巍.2004-每一刻都是崭新的【步升大风】【WAV+CUE】
- 群星.2024-四方馆影视原声带【韶愔音乐】【FLAC分轨】
- 陈雷.1997-安锁咧【金圆唱片】【WAV+CUE】
- 关淑怡.2013-MY.FAVORITE.SK.3CD【环球】【WAV+CUE】
- Sweety.2006-花言乔语【丰华】【WAV+CUE】
- 李恕权.2003-回·20年全精选2CD【SONY】【WAV+CUE】