python之sort高级用法

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 keys
student_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 attributes
class 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, attrgetter
sorted(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'))




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值