Python sorted() 函數(shù)
sorted() 函數(shù)對所有可迭代的對象進行排序操作
sorted 語法:
sorted(iterable, key=None, reverse=False)
參數(shù)說明:
iterable
– 可迭代對象。
key
– 主要是用來進行比較的元素,只有一個參數(shù),具體的函數(shù)的參數(shù)就是取自于可迭代對象中,指定可迭代對象中的一個元素來進行排序。
reverse
– 排序規(guī)則,reverse = True 降序 , reverse = False 升序(默認)。
1、對字典按鍵(key)進行排序
1
2
3
4
|
dir_info = { 'a' : 1 , 'd' : 8 , 'c' : 3 , 'b' : 5 } #對字典按鍵(key)進行排序(默認由小到大) dir_sort = sorted (dir_info.items(),key = lambda x:x[ 0 ]) print (dir_sort) |
輸出結(jié)果:
[('a', 1), ('b', 5), ('c', 3), ('d', 8)]
直接對字典的key排序
1
|
sorted ({ 'a' : 1 , 'd' : 8 , 'c' : 3 , 'b' : 5 }.keys()) |
2、對字典按值(value)進行排序
1
2
3
4
|
dir_info = { 'a' : 1 , 'd' : 8 , 'c' : 3 , 'b' : 5 } #對字典按鍵(key)進行排序(默認由小到大) dir_sort = sorted (dir_info.items(),key = lambda x:x[ 1 ]) print (dir_sort) |
輸出結(jié)果
[('a', 1), ('c', 3), ('b', 5), ('d', 8)]
直接對字典的value排序
1
|
sorted ({ 'a' : 1 , 'd' : 8 , 'c' : 3 , 'b' : 5 }.values()) |
解析:
dir_info.items()
是獲得了字典的key,value 兩個參數(shù)
dir_info[0]
表示按照第一元素進行排序
dir_info[1]
表示按照第二個元素進行排序
為了便于理解,再舉個例子
1
2
3
|
person_info = [( 'zhangsan' , '男' , 15 ), ( 'lisi' , '男' , 12 ), ( 'wangwu' , '男' , 10 ),] person_sort = sorted (person_info, key = lambda x: x[ 2 ]) print (person_sort) |
輸出結(jié)果:
[('wangwu', '男', 10), ('lisi', '男', 12), ('zhangsan', '男', 15)]
當(dāng)然key的形式也是多樣的
比如:
1.按照字符串長度進行排序
1
|
key = lambda x: len (x) |
2.先按照第一個元素,再按照第二個元素:
1
|
key = lambda x : (x[ 0 ] , x[ 1 ]) |
擴展:
將列表中數(shù)據(jù)的某一部分作為關(guān)鍵字進行排序(選取標(biāo)志性可用于排序的元素作為條件)
1
2
3
|
list_info = [ 'test-10.txt' , 'test-11.txt' , 'test-22.txt' , 'test-14.txt' , 'test-3.txt' , 'test-20.txt' ] list_sort = sorted (list_info, key = lambda d : int (d.split( '-' )[ 1 ].split( '.' )[ 0 ])) print (list_sort) |
輸出結(jié)果
['test-3.txt', 'test-10.txt', 'test-11.txt', 'test-14.txt', 'test-20.txt', 'test-22.txt']
以上就是Python教程按照字典的鍵或值進行排序方法解析的詳細內(nèi)容,更多關(guān)于Python按照字典的鍵或值進行排序的資料請關(guān)注服務(wù)器之家其它相關(guān)文章!
原文鏈接:https://blog.csdn.net/weixin_47906106/article/details/119378398