Python 中的排序
来源:互联网 发布:finale mac 编辑:程序博客网 时间:2024/05/16 00:46
早在学习perl的时候就总结过排序问题 Schwartzian Transform(施瓦茨变换)
现在,我们来看看在python中如何实现:
Schwartzian transform的中心思想就是Decorate-Sort-Undecorate
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))s1 = Student('Ace', 'S', 12)s2 = Student('David', 'A', 10)s3 = Student('Jie', 'S', 13)s4 = Student('Shawn', 'A', 11)students = [ s1, s2, s3, s4 ]decorated = [(s.grade, s.age, s) for s in students]decorated.sort()#undecoratesorted_students = [ s for _,_,s in decorated ]print sorted_students# [('David', 'A', 10), ('Shawn', 'A', 11), ('Jie', 'S', 12), ('Ace', 'S', 13)]
当然,既然用了python,就应该pythonic到底,试试下面的方法吧:
print sorted(students, key=lambda s: s.grade and s.age)
from operator import attrgetterprint sorted(students, key=attrgetter('grade', 'age'))
0 0
- Python中的排序
- python中的归并排序
- Python中的排序
- python中的字典排序!
- python 字典中的排序
- python中的排序
- Python中的字典排序
- Python 中的排序
- python中的排序
- python 中的排序大法
- Python中的排序
- python中的排序
- python中的排序和numpy中的排序
- python中的列表排序操作
- Python中的对象的排序
- Python 中的列表排序函数
- 【Python】Python_learning2:python中的冒泡排序
- Python(8) python中的冒泡排序、快速排序
- NDK开发-初识NDK
- Jersey发布图片到另一台图片服务器
- Android 信息提示Dialog、Toast和Snackbar
- 介绍JavaScript中的四个陷阱
- java读取数据库数据并导出到EXCEL中
- Python 中的排序
- 解决Cannot change version of project facet Dynamic web module to 2.5
- 深入Java虚拟机之基于栈指令的解释器执行引擎
- Andrew Ng机器学习课程(一) - Python梯度下降实战
- MyBatis-搭建MyBatis开发环境一(MyEclipse版)
- js 去处数组中重复的对象
- LeetCode | Scramble String
- C#读取txt文件
- Dijkstra、Bellman_Ford、SPFA、Floyd算法复杂度比较