Python排序指南——sorted()函数和.sort()方法知识点汇总
2019-10-15 18:21
621 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/PigeonKiing/article/details/102572204
内置的list.sort()方法可以直接修改列表;sorted()内置函数会从一个可迭代对象构建一个新的排序列表。
基本排序
sorted()函数
简单的升序排列,调用sorted()函数,会返回一个新的已排序列表。
>>> sorted([5, 2, 3, 1, 4]) [1, 2, 3, 4, 5]
list.sort()方法
list.sort() 方法,它会直接修改原列表。
>>> a = [5, 2, 3, 1, 4] >>> a.sort() >>> a [1, 2, 3, 4, 5]
list.sort() 方法只是为列表定义的,而sorted() 函数可以接受任何可迭代对象。
>>> sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'}) [1, 2, 3, 4, 5]
关键(key)函数
list.sort() 和sorted() 都有一个key 形参来指定在进行比较之前要在每个列表元素上进行调用的
函数。
>>> sorted("This is a test string from Andrew".split(), key=str.lower) ['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']
key 形参的值应该是一个函数,它接受一个参数并并返回一个用于排序的键。
这种技巧速度很快,因为对于每个输入记录只会调用一次key 函数。
一种常见的模式是使用对象的一些索引作为键对复杂对象进行排序。例如:
>>> student_tuples = [ ... ('john', 'A', 15), ... ('jane', 'B', 12), ... ('dave', 'B', 10), ... ] >>> sorted(student_tuples, key=lambda student: student[2]) # sort by age [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
升序和降序
list.sort() 和sorted() 接受布尔值的reverse 参数。这用于标记降序排序。
例如,要以反向age 顺序获取学生数据:
>>> sorted(student_tuples, key=x:x[2], reverse=True) [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
表示将列表按照每个数据元素的第三项进行降序排列。
相关文章推荐
- python中列表排序sort()方法或者内建函数sorted()
- python中的排序函数sorted以及列表排序方法sort()
- python的排序函数sort,sorted在列表排序和字典排序中的应用详解和举例
- python列表排序方法sort、sorted技巧篇
- python容器排序sort()和内建函数sorted()的区别
- python中List的sort方法(或者sorted内建函数)的用法
- python 中的排序方法:sorted() 和 sort()
- Python 列表排序方法reverse、sort、sorted详解
- Python的排序函数Sort,Sorted
- Python中的排序函数argsort,sort,sorted
- python的排序函数sort,sorted在列表排序和字典排序中的应用详解和举例
- python 列表排序方法sort、sorted技巧篇
- python中List的sort方法(或者sorted内建函数)的用法
- python 中方法 sort() 和函数sorted()的区别!!!!
- Python之排序函数sort() 和 sorted()
- python中List的sort方法(或者sorted内建函数)的用法
- python 列表排序方法reverse、sort、sorted详解
- Python 列表排序方法reverse、sort、sorted详解
- python 列表排序方法reverse、sort、sorted基础篇
- Python 列表排序方法reverse、sort、sorted详解