将一个列表进行升序排序可以简单的调用sorted()函数:
>>> a = [random.randint(1,21) for i in range(20)]
>>> a
[15, 10, 10, 18, 13, 8, 4, 9, 20, 9, 15, 15, 19, 15, 11, 5, 18, 19, 6, 1]
>>> sorted(a)
[1, 4, 5, 6, 8, 9, 9, 10, 10, 11, 13, 15, 15, 15, 15, 18, 18, 19, 19, 20]
>>> a
[15, 10, 10, 18, 13, 8, 4, 9, 20, 9, 15, 15, 19, 15, 11, 5, 18, 19, 6, 1]
或者可以调用列表的list.sort()方法,它对列表进行原地排序并且返回None。
>>> a.sort()
>>> a
[1, 4, 5, 6, 8, 9, 9, 10, 10, 11, 13, 15, 15, 15, 15, 18, 18, 19, 19, 20]
有一点不同的是list.sort()是为list定义的,而sorted()可以接受任意可迭代类型的对象。
>>> sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'})
[1, 2, 3, 4, 5]
自2.4版本以后,list.sort()和sorted()函数都增加了key参数,参数指明在应用comparisons之前对列表中的每个元素都调用一个函数进行预处理:
>>> sorted("This is a test string from Andrew".split(), key=str.lower)
['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']
key参数指明的函数有一个单一的传入参数,并且返回一个用以排序的键:
student_tuples = [
('john', 'A', 15),
('jane', 'B', 12),
('dave', 'B', 10),]
print sorted(student_tuples, key=lambda student: student[2]) # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
同样的策略可以应用在类对象上,例:
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),
]
print sorted(student_objects, key=lambda student: student.age) # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
应用operator模块中的itemgetter,attrgetter以及methodcaller函数可以是上述操作更加简单快捷:
from operator import itemgetter, attrgetter
print sorted(student_tuples, key=itemgetter(2))
print sorted(student_objects, key=attrgetter('age'))
operator模块中的函数可以实现多维度混合排序(多个关键字作为排序键值),例如:
print sorted(student_tuples, key=itemgetter(1,2))
print sorted(student_objects, key=attrgetter('grade', 'age'))
list.sort()和sort()函数接收一个reverse参数(布尔值),这个参数用以标示降序排序,例如:
print sorted(student_tuples, key=itemgetter(2), reverse=True)
[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
自版本2.2开始,Python排序都会保证其稳定性,例如:
data = [('red', 1), ('blue', 1), ('red', 2), ('blue', 2)]
print sorted(data,key = itemgetter(0))
#[('blue', 1), ('blue', 2), ('red', 1), ('red', 2)]
在python2.x版本中,sorted()和list.sort()都支持cmp参数来处理用户自定义的比较函数。Python3.0中,cmp参数被完全废止。旧式的cmp参数用法:
def numeric_compare(x, y):
return x - y
print sorted([5, 2, 4, 1, 3], cmp=numeric_compare)
#[1, 2, 3, 4, 5]
def reverse_numeric(x, y):
return y - x
print sorted([5, 2, 4, 1, 3], cmp=reverse_numeric)
#[5, 4, 3, 2, 1]
REF:https://wiki.python.org/moin/HowTo/Sorting/