码迷,mamicode.com
首页 > 编程语言 > 详细

Python sorted函数排序

时间:2017-11-11 14:18:58      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:学生   一个   获取对象   关于   operator   max   getter   定义   cheng   

 

学生先按名称排序,在按成绩排序

 

from operator import itemgetter
students=[(‘Bob‘,90),(‘David‘,99),(‘Dacheng‘,96),(‘Max‘,94)]
sorted(students,key=itemgetter(0))
sorted(students, key=lambda t: t[1])
#sorted(students,key=itemgetter(1))

 

关于itemgetter函数:operator.itemgetter函数获取的不是值,而是定义了一个函数,通过该函数作用到对象上才能获取值。

a = [1,2,3] 
>>> b=operator.itemgetter(1)      //定义函数b,获取对象的第1个域的值
>>> b(a) 

>>> b=operator.itemgetter(1,0)  //定义函数b,获取对象的第1个域和第0个的值
>>> b(a) 
(2, 1)

Python sorted函数排序

标签:学生   一个   获取对象   关于   operator   max   getter   定义   cheng   

原文地址:http://www.cnblogs.com/daacheng/p/7818812.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!