python dic字典排序
使用lambda匿名函数来实现。
>>> dic1 = {‘a‘:1,‘b‘:2,‘e‘:5,‘d‘:4,‘c‘:3} >>> result = sorted(dic1.items(), key = lambda x :(x[1])) >>> result [(‘a‘, 1), (‘b‘, 2), (‘c‘, 3), (‘d‘, 4), (‘e‘, 5)] >>> result = sorted(dic1.items(), key = lambda x :(-x[1])) >>> result [(‘e‘, 5), (‘d‘, 4), (‘c‘, 3), (‘b‘, 2), (‘a‘, 1)] >>> dic1 {‘a‘: 1, ‘b‘: 2, ‘e‘: 5, ‘d‘: 4, ‘c‘: 3} >>> result = sorted(dic1.items(), key = lambda x :(x[0])) >>> result [(‘a‘, 1), (‘b‘, 2), (‘c‘, 3), (‘d‘, 4), (‘e‘, 5)] >>> result = sorted(dic1.items(), key = lambda x :(x[0]),reverse = True) >>> result [(‘e‘, 5), (‘d‘, 4), (‘c‘, 3), (‘b‘, 2), (‘a‘, 1)] #x[0] 用字典的第一位排序 #x[1] 用字典的第二位排序 #-x[0] 用第一位的负数排序 默认是升序 reverse = True 降序
这个用的比较多,先记录一下。写给自己看。
读书和健身总有一个在路上
相关推荐
zhaojikun 2019-05-09
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