标签:val list nbsp lin div containe table from padding
按照字典值的大小对字典进行排序
1. 利用zip函数将key值和value值位置进行颠倒,再使用sorted进行排序
例如:
1
2
3
4
5
6
7
8
|
from random import randint d = {k:randint( 0 , 20 ) for k in ‘abcdefg‘ } #{‘f‘: 10, ‘g‘: 16, ‘a‘: 18, ‘c‘: 12, ‘e‘: 16, ‘d‘: 7, ‘b‘: 16} z = list ( zip (d.values(),d.keys())) # zip函数就是将输入的序列重新组合成每个元素都是元组的列表,其中每个元素由输入序列相同位置的元素组成 #[(10, ‘f‘), (16, ‘g‘), (18, ‘a‘), (12, ‘c‘), (16, ‘e‘), (7, ‘d‘), (16, ‘b‘)] print ( sorted ( zip (d.values(),d.keys()))) #[(7, ‘d‘), (10, ‘f‘), (12, ‘c‘), (16, ‘b‘), (16, ‘e‘), (16, ‘g‘), (18, ‘a‘)] |
2.利用匿名函数进行排序
1
2
|
print ( sorted (d.items(),key = lambda k : k[ 1 ])) #[(‘d‘, 7), (‘f‘, 10), (‘c‘, 12), (‘g‘, 16), (‘e‘, 16), (‘b‘, 16), (‘a‘, 18)] |
3. 使用operator.itemgetter函数
1
2
3
|
import operator print ( sorted (d.items(), key = operator.itemgetter( 1 ))) #[(‘d‘, 7), (‘f‘, 10), (‘c‘, 12), (‘g‘, 16), (‘e‘, 16), (‘b‘, 16), (‘a‘, 18)] |
标签:val list nbsp lin div containe table from padding
原文地址:http://www.cnblogs.com/BGPYC/p/7501374.html