python sorted函数以及operator.itemgetter函数 - Go语言中文社区

python sorted函数以及operator.itemgetter函数


参考:

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

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

《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))

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




版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/u012005313/article/details/49154683
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-03-08 11:33:05
  • 阅读 ( 1064 )
  • 分类:

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢