sorted 用法详解,来源于官方文档

时间:2021-08-11 23:27:55
#sorted用法

#1
a=sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'})

print(a)
##[1, 2, 3, 4, 5]

#2
b=sorted("This is a test string from Andrew".split(), key=str.lower,reverse=True)
print(b)


#3
student_tuples = [
    ('john', 'A', 15),
     ('jane', 'B', 12),
     ('dave', 'B', 10),
]
res=sorted(student_tuples, key=lambda student: student[2])   # sort by age
print(res)
##[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]


#4
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))



student_objects = [
    Student('john', 'A', 15),
    Student('jane', 'B', 12),
    Student('dave', 'B', 10),
]
d=sorted(student_objects, key=lambda student: student.age)   # sort by age
print(d)

#5复杂排序:
##Operator Module Functions
##The key-function patterns shown above are very common, so Python provides convenience functions to make accessor functions easier and faster. The operator module has itemgetter(), attrgetter(), and a methodcaller() function.
##
##Using those functions, the above examples become simpler and faster:


print('test 5')
from operator import itemgetter, attrgetter

print(sorted(student_tuples, key=itemgetter(2)))
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

sorted(student_objects, key=attrgetter('age'))
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]


print('test6')
##The operator module functions allow multiple levels of sorting. For example, to sort by grade then by age:
print(sorted(student_tuples, key=itemgetter(1,2)))
[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]

sorted(student_objects, key=attrgetter('grade', 'age'))
[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]

print('test99,my test')
print(sorted(student_tuples,key=lambda student: str(student[1]) + str(student[2])))