python之sort高级用法
来源:互联网 发布:淘宝黑科技 编辑:程序博客网 时间:2024/06/04 01:16
both list.sort() and sorted() added a key parameter to specify a FUNCTION to be called on each list element prior to making comparisons.
而且通过通过设置reverse可以颠倒排序结果
#注意key后的是function,不是function call的值, 所以常用lambda表达式sorted("This is a test string".split(), key=str.lower)----------------------------------------['This', 'test', 'string', 'is', 'a']#A common pattern is to sort complex objects using some of the object’s indices as keysstudent_tuples = [('john', 'A', 15),('jane', 'B', 12),('dave', 'B', 10),]sorted(student_tuples, key=lambda student: student[2])----------------------------------------[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]#The same technique works for objects with named attributesclass Student(object): 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_objects = [Student('John', 'A', 15), Student('Jane', 'B', 12), Student('Dave', 'B', 10),]sorted(student_objects, key=lambda student: student.age)------------------------------------------[('Dave', 'B', 10), ('Jane', 'B', 12), ('John', 'A', 15)]#上面都可以一些python内置的函数from operator import itemgetter, attrgettersorted(student_tuples, key=itemgetter(2))sorted(student_objects, key=attrgetter('age'))sorted(student_tuples, key=itemgetter(1,2))sorted(student_objects, key=attrgetter('grade', 'age'))
0 0
- python之sort高级用法
- python sort、sorted 高级用法
- Python 列表的sort()方法之高级排序
- linux之sort用法
- linux之sort用法
- linux之sort用法
- linux之sort用法
- linux之sort用法
- linux之sort用法
- linux之sort用法
- linux之sort用法
- linux之sort用法
- linux之sort用法
- linux之sort用法
- linux之sort用法
- linux之sort用法
- linux之sort用法
- linux之sort用法
- Android中通过广播方式调起第三方App
- php读取服务器(CentOS 6.5)状态并存入数据库
- Java基础——IO流(上)之字符流
- Android 手机短信简单开发
- linux nc命令参数及用法详解--功能超级强大的网络工具netcat
- python之sort高级用法
- IOS: 图像处理
- 使用git进行版本控制
- 第九周 程序阅读-字符串类的设计
- c/c++中指针
- 黑马程序员----[20150508][IO流2]
- [ios]in house类型应用发布到内部服务器
- 编程的宗派
- Java web基础总结三之—— java web 服务器