python sorted函数以及operator.itemgetter函数

来源:互联网 发布:vb crc教程 编辑:程序博客网 时间:2024/05/29 08:52

参考:

http://www.cnblogs.com/100thMountain/p/4719503.html

http://blog.163.com/zhuandi_h/blog/static/1802702882012111284632184/

《Machine Learning In Action》第二章

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


operator.itemgetter函数:

import operatorhelp(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))

进行多级排序,即先跟第三个域进行排序,再根据第二个域排序(反过来了)




0 0
原创粉丝点击