zhaojikun 2019-05-09
字典按照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)]
f = lambda x, y, z: x + y + z # returns a function that can optionally be assigned a name. def func: