python 对字典按照value进行排序的方法
字典按照value进行排序共有三种方法
d = {'a': 1, 'b': 4, 'c': 2, 'f' : 12} # 第一种方法,key使用lambda匿名函数取value进行排序 a = sorted(d.items(), key=lambda x: x[1]) a1 = sorted(d.items(),key = lambda x:x[1],reverse = True) # key使用lambda匿名函数按键进行排序 a2 = sorted(d.items(),key = lambda x:x[0]) # 第二种方法使用operator的itemgetter进行排序 import operator b = sorted(d.items(), key=operator.itemgetter(1)) # 第三种方法讲key和value分装成元祖,在进行排序 f = zip(d.keys(), d.values()) c = sorted(f) print(a) print(a1) print(a2) print(b) print(c)
打印结果是:
[('a', 1), ('c', 2), ('b', 4), ('f', 12)]
[('f', 12), ('b', 4), ('c', 2), ('a', 1)]
[('a', 1), ('b', 4), ('c', 2), ('f', 12)]
[('a', 1), ('c', 2), ('b', 4), ('f', 12)]
[('a', 1), ('b', 4), ('c', 2), ('f', 12)]
相关推荐
meylovezn 2020-09-21
mmmjyjy 2020-07-16
typhoonpython 2020-06-11
x青年欢乐多 2020-06-06
Stranger 2020-05-16
PythonMaker 2020-04-22
QianYanDai 2020-04-18
千锋 2020-04-11
SDUTACM 2020-03-05
fly00love 2020-03-05
f = lambda x, y, z: x + y + z # returns a function that can optionally be assigned a name. def func:
sschencn 2020-02-21
wklken的笔记 2020-01-30
GhostLWB 2020-01-30
sulindong0 2020-01-19
chinademon 2020-01-12
mieleizhi0 2020-01-11