赞
踩
函数原型:
L.sort(*, key=None, reverse=None)
它把 L
原地排序,也就是使用后并不是返回一个有序的序列副本,而是把当前序列变得有序!
参数说明:
argument | description |
---|---|
* | 迭代类型的数据列表 |
key | 函数类型,比较的原则 |
reverse | 为 True 时逆序 |
Both list.sort() and sorted() have a key parameter to specify a function (or other callable) to be called on each list element prior to making comparisons.
首先定义一个 Student 类,每一个对象有学号 num
和名字 name
两个属性,对 Student 列表元素排序
class Student:
class Student:
def __init__(self, num, name):
self.num = num
self.name = name
def __str__(self):
return f'{self.num} - {self.name}'
List:
students = [
Student(5, 'Tom'),
Student(2, 'Tony'),
Student(6, 'Lucy'),
Student(1, 'Jerry')
]
key 接受的函数类型要求 函数只有一个参数,默认按返回值的升序对列表元素排序:
cmp2 = lambda stud: stud.num
students.sort(key=cmp2, reverse=False)
for student in students:
print(student)
结果如下:
1 - Jerry
2 - Tony
5 - Tom
6 - Lucy
当比较函数有 2 个参数时,如:
def mycmp(stud1, stud2):
''' return true when num is greater'''
return stud1.num - stud2.num
此时需要用到 functools.cmp_to_key()
:
from functools import cmp_to_key
cmp1 = lambda stud1, stud2: stud1.num - stud2.num
students.sort(key=cmp_to_key(cmp1))
for student in students:
print(student)
结果如下:
1 - Jerry
2 - Tony
5 - Tom
6 - Lucy
类似的,max
函数也有参数 key:
a = [('x', 5), ('y', 3), ('z', 8)]
print(max(a, key=lambda x: x[-1])) # ('z', 8)
完结
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。