python sorted對列表和字典排序

2021-09-10 23:19:15 字數 1312 閱讀 7281

sorted函式引數:

sorted(data, key=none, reverse=false)
其中,data是待排序資料,可以是list或者iterator, cmp和key都是函式,這兩個函式作用於data的元素上產生乙個結果,sorted方法根據這個結果來排序。 

key 是帶乙個引數的函式, 用來為每個元素提取比較值. 預設為 none, 即直接比較每個元素. 

reverse=true則是倒序,reverse=false時則是順序,預設時reverse=false

#列表排序例子

example = [('張三', 'a', 85), ('李四', 'c', 60), ('王五', 'b', 95)]#姓名、級別、分數

#用key排序

sorted(example, key=lambda x : x[1]) # 按級別排序

#out:[('張三', 'a', 85), ('王五', 'b', 95), ('李四', 'c', 60)]

sorted(example, key=lambda x : x[2]) # 按分數排序

#out: [('李四', 'c', 60), ('張三', 'a', 85), ('王五', 'b', 95)]

#用 operator 函式來加快速度

from operator import itemgetter

sorted(example, key=itemgetter(2))

#out: [('李四', 'c', 60), ('張三', 'a', 85), ('王五', 'b', 95)]

#用 operator 函式進行多級排序

sorted(example, key=itemgetter(1,2))#先按分數再按級別

#out: [('張三', 'a', 85), ('王五', 'b', 95), ('李四', 'c', 60)]

#字典排序例子

d=#對key值排序

sorted(d.keys())

#out: ['a', 'b', 'c']

#按value值對字典排序

sorted(d.items(),key=lambda x:x[1])#

#out: [('c', 60), ('a', 85), ('b', 95)]

#按key值對字典排序

sorted(d.items(),key=lambda x:x[0])

#out:[('a', 85), ('b', 95), ('c', 60)]

如果對你有幫助,請點下讚,予人玫瑰手有餘香!

Python sorted對字典和列表進行排序

1.按鍵值對對字典進行排序 sorted iterable,key,reverse sorted一共有iterable,key,reverse這三個引數。其中iterable表示可以迭代的物件,例如可以是dict.items dict.keys 等,key是乙個函式,用來選取參與比較的元素,reve...

python sorted函式對元組排序

按照二元組的其中乙個元素排序 print degree sequence h.degree h degree sequence sorted n,d for n,d in h.degree reverse false print this is h degree sequence in functi...

python sorted方法和列表使用解析

一 基本形式列表有自己的sort方法,其對列表進行原址排序程式設計客棧,既然程式設計客棧是原址排序,那顯然元組不可能擁有這種方法,因為元組是不可修改的。排序,數字 字串按照ascii,中文按照unicode從小到大排序 如果有乙個人排序好的副本,同時保持原有的列表不變,怎麼實現呢?注意 y x通過分...