Article Directory
Python list has a built-in sort() method for sorting. You can also use Python’s built-in global sorted() method to sort an iterable sequence to generate a new sequence.
1 Basic form
The list has its own sort method, which sorts the list in-situ. Tuples are not allowed, tuples cannot be modified
>>> a = [3,6,1,8,0,5,7,9,2,4]
>>> a.sort()
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a = [3,6,1,8,0,5,7,9,2,4]
>>> res = sorted(a)
>>> a
[3, 6, 1, 8, 0, 5, 7, 9, 2, 4]
>>> res
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
2 Complex list
2.1 The content of the list is a tuple
student = [
('john', 'A', 15),
('jane', 'B', 12),
('dave', 'B', 10),
]
res = sorted(student, key=lambda student: student[2]) # sort by age
print(res)
operation result:
2.2 List content is class
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))
students = [
Student('john', 'A', 15),
Student('jane', 'B', 12),
Student('dave', 'B', 10),
]
res = sorted(students, key=lambda s: s.age)
print(res)
2.3 The content of the list is a dictionary
student = [
{
"name": "xiaoming", "score": 60},
{
"name": "daxiong", "score": 20},
{
"name": "maodou", "score": 30},
]
res = sorted(student, key=lambda d:d['score'])
print(res)
2.4 itemgetter and attrgetter
Python provides operator.itemgetter and attrgetter to improve execution speed
from operator import itemgetter, attrgetter
stu = [
("A", 30),
("B", 20),
("C", 10)
]
print(sorted(stu, key=itemgetter(1)))
#operator提供了多个字段的复杂排序,先对第0个字段排序,再对第一个字段排序
print(sorted(stu, key=itemgetter(0,1)))
from operator import itemgetter, attrgetter
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))
stu = [
Student('jane', 'B', 12),
Student('john', 'A', 12),
Student('dave', 'B', 10),
]
# 对students按照年龄排序
print(sorted(stu, key=attrgetter('age')))
# 其等价于
print(sorted(stu, key=lambda o: o.age))
# 也可以按多个key排序, 先按age再按grade排序
print(sorted(stu, key=attrgetter('age', 'grade')))
operation result:
3 Sort the dictionary
Sorting the dictionary returns a list, you can sort the key, you can sort the value, you can also sort the items
d = {
1: 'D', 2: 'C', 3: 'B', 4: 'A'}
print(sorted(d))
print(sorted(d.values()))
print(sorted(d.items()))
operation result
4 cmp_to_key (customized comparison function)
After python3, the cmp parameter in the sort method and the sorted function is cancelled. If you still need to use a custom comparison function, you can use the cmp_to_key function. Use with tools that accept key function (such as sorted(), min(), max(), heapq.nlargest(), itertools.groupby())
from functools import cmp_to_key
a = [3, 6, 1, 8, 0, 5, 7, 9, 2, 4]
def cmp(x, y):
if x > y:
return -1
elif x < y:
return 1
else:
return 0
b = sorted(a, key=cmp_to_key(cmp))
print(b)
operation result