Python的attrgetter()
来源:互联网 发布:centos minimal 区别 编辑:程序博客网 时间:2024/06/04 18:28
# -*- coding: utf-8 -*-# 在排序时, 可以用lambda表达式将对象map成keys# 亦可以使用operator包中的attrgetter和itemgetter函数以提高效率# 参考 http://wiki.python.org/moin/HowTo/Sorting# 考虑 Student 对象class Student: def __init__(self, name, grade, age): self.name = name self.grade = grade self.age = age def __repr__(self): return repr((self.name, self.grade, self.age))# 建立一组Student对象students = [ Student('jane', 'B', 12), Student('john', 'A', 12), Student('dave', 'B', 10),]from operator import itemgetter, attrgetter# 对students按照年龄排序print sorted(students, key=attrgetter('age'))# 其等价于print sorted(students, key=lambda o: o.age)# 输出: >>> [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]# 亦可以按多个key排序, 先按age再按grade排序print sorted(students, key=attrgetter('age', 'grade'))# 输出: >>> [('dave', 'B', 10), ('john', 'A', 12), ('jane', 'B', 12)]
0 0
- Python的attrgetter()
- python attrgetter()
- Python 内置函数sorted详解和itemgetter, attrgetter
- 【Python】Python 百分号 % 的意思
- python以及python的由来
- 【python】python的方法覆盖
- 【python】python的socket编程
- 【python】python的unittest使用
- [Python]Python oop的私有制
- [Python]这次的Python作业
- 【Python】Python的类型转换
- 【python】查看python的版本号
- 【Python】Ceph的python接口
- Python-1 python的开始
- Python-5 Python的循环
- 【Python】Ceph的python接口
- Awesome python (了不起的python)
- Python学习-Python的基础知识
- linux mysql增加用户,删除用户,以及用户权限
- 【原创】IMSDroid学习之一:编译doubango for android
- POJ 2456 二分
- httpxml.send->拒绝访问错误80070005的解决方法
- 简单实现EditText右侧删除按钮
- Python的attrgetter()
- OpenScad的学习笔记
- javascript中的回调函数
- APP审核驳回和重大版本问题经典案例及解决方案
- 如何在Flex 4 中使用新的CSS语法
- linux下网卡漂移导致网络不可用
- HDU - 5215 Cycle(奇圈和偶圈)
- 从UE4开始蜕变
- DIY系列之Web浏览器(1)——Javascript