1. 程式人生 > >python sorted函式以及operator.itemgetter函式

python sorted函式以及operator.itemgetter函式

參考:

《Machine Learning In Action》第二章

###############################################################

operator.itemgetter函式:

import operator
help(operatpr.itemgetter)

operator模組提供的itemgetter函式用於獲取物件的哪些維的資料,引數為一些序號(即需要獲取的資料在物件中的序號)

a=[1,2,3]
b=operator.itemgetter(1) #定義函式b,獲取物件的第一個域的值
b(a)
b=operator.itemgetter(1,0)#定義函式b,獲取物件的第1個域和第0個域的值
b(a)


note that:operator.itemgetter函式獲取的不是值,而是定義了一個函式,通過該函式作用到物件上才能獲取值。

##################################################################

sorted函式

sorted函式是內建函式

help(sorted)


引數解釋:

iterable:指定為要排序的list或iterable物件

cmp:接受一個函式(有兩個引數),指定排序時進行比較的函式,可以指定一個函式或lambda表示式,如:

stu=[('jhon', 'a', 15), ('jane', 'b', 12), ('save', 'b', 10)]
def f(a,b):
    return a-b
 sorted(stu, cmp=f)


key:接受一個函式(只有一個引數),指定待排序元素的哪一項進行排序:

sorted(stu, key=lambda student:student[2])

reverse:是一個bool變數,表示升序還是降序排列,預設為false(升序排列),定義為True時表示降序排列

#####################################################################################

sorted函式和operator.itemgetter函式的使用

stu=[('jhon', 'a', 15), ('jane', 'b', 12), ('save', 'b', 10)]
sorted(students, key=operator.itemgetter(2))

通過stu的第三個域進行排序
sorted(students, key=operator.itemgetter(1,2))

進行多級排序,即先跟第三個域進行排序,再根據第二個域排序(反過來了)