operator.itemgetter函数
来源:互联网 发布:h.264网络硬盘录像机 编辑:程序博客网 时间:2024/06/08 11:52
转载:
operator.itemgetter函数
operator模块的itemgetter函数:获取对象的哪些维的数据,参数为序号(即需要获取的数据在对象中的序号)
例如:
a = [1,2,3]
》b=operator.itemgetter(1) //定义函数b,获取对象的第2个值
》 b(a)
2
》b=operator.itemgetter(1,0) //定义函数b,获取对象的第2个和第1个的值
》b(a)
(2, 1)
注意,operator.itemgetter函数获取的不是值,而是定义了一个函数,通过该函数作用到对象上才能获取值。
*sorted函数
*
Python内置的排序函数sorted可以对list或者iterator进行排序,官网文档:
http://docs.python.org/2/library/functions.html?highlight=sorted#sorted,
原型:sorted(iterable[, cmp[, key[, reverse]]])
(1)iterable:排序的list或者iterable(迭代对象)
(2)cmp为函数,指定排序时进行比较的函数,可以指定一个函数或者lambda函数,
如:
students为类对象的list,每个成员有三个域,用sorted进行比较时可以自己定cmp函数,例如这里要通过比较第三个数据成员来排序,代码可以这样写:
students = [(‘john’, ‘A’, 15), (‘jane’, ‘B’, 12), (‘dave’, ‘B’, 10)]
sorted(students, key=lambda student : student[2])
(3)key为函数,指定取待排序元素的哪一项进行排序,函数用上面的例子来说明,代码如下:
sorted(students, key=lambda student : student[2])
key指定的lambda函数功能是取元素student的第三个域(即:student[2]),因此sorted排序时,会以students所有元素的第三个域来进行排序。
operator.itemgetter函数来实现,例如上例,可以这么写:
sorted(students, key=operator.itemgetter(2))
sorted函数也可以进行多级排序,例如要根据第二个域和第三个域进行排序,可以这么写:
sorted(students, key=operator.itemgetter(1,2))
先根据第二个域排序,再根据第三个域排序。
(4)reverse参数bool变量,默认为false(升序排列)
- operator.itemgetter函数
- python中的operator.itemgetter函数 operator.itemgetter函数
- python operator.itemgetter函数 sorted函数
- python sorted函数以及operator.itemgetter函数
- sorted函数以及operator.itemgetter函数
- python sorted函数以及operator.itemgetter函数
- Python-sorted函数和operator.itemgetter函数
- Python3:operator模块中的itemgetter()函数
- python排序sorted()与operator.itemgetter()函数
- Python中的sorted函数以及operator.itemgetter函数
- Python中的sorted函数以及operator.itemgetter函数
- Python中的sorted函数以及operator.itemgetter函数 【转载】
- Python 中sorted函数和operator.itemgetter函数
- Python中的sorted函数以及operator.itemgetter函数 【转载】
- Python中的sorted()函数以及operator.itemgetter()函数
- Python中的sorted函数以及operator.itemgetter函数
- Python中的sorted函数以及operator.itemgetter函数
- Python中的sorted函数以及operator.itemgetter函数
- G
- 数据库引擎
- GeoHash算法小记
- python 装饰器
- 新的生活
- operator.itemgetter函数
- [笔记]解决git clone 子模块没下载全的问题
- AtCoder 3596(拓扑排序的思想)
- 关于c语言中double指针的初始化问题
- 42. Trapping Rain Water
- Notepad++ 7.5.1 没有找到plugin manager的解决办法
- java常用正则表达式
- SQL和HQL的区别
- CORS解决跨域问题