使用sorted函数对python中的迭代对象进行排序


#Python#


2014-10-12

本文的python版本是2.7。

python中列表自带了一个会改变自身的sort()函数:

>>> a=[1, 3, 5, 2]
>>> a
[1, 3, 5, 2]
>>> a.sort()
>>> a
[1, 2, 3, 5]

其实,python也内置了一个很棒的sorted()函数,利用该函数可以对列表、字典等可迭代对象进行排序,它是返回一个包含排序结果的列表,并不会改变被排序的对象。

比如,对列表:

>>> a=[1, 3, 5, 2]
>>> sorted(a)  # 升序
[1, 2, 3, 5]
>>> sorted(a, reverse=True)  # 降序
[5, 3, 2, 1]

>>> a
[1, 3, 5, 2]

对元组(tuple):

>>> a=(1, 3, 5, 2)
>>> sorted(a)
[1, 2, 3, 5]
>>> a
(1, 3, 5, 2)

对字典而言,其可以按照键来排序,也可以按照值来排序。当然,首先需要将字典转换为可迭代对象:

>>> a = {100:6, 200:3, 60:9}
>>> a.items()
[(200, 3), (60, 9), (100, 6)]

根据键来排序:

>>> sorted(a.items(), key = lambda item: item[0])
[(60, 9), (100, 6), (200, 3)]

根据值来排序:

>>> sorted(a.items(), key = lambda item: item[1])
[(200, 3), (100, 6), (60, 9)]

从列表的例子中可以看出,sorted()可以处理比较复杂的结构,在官方的手册中也给出了比较复杂的例子,例如:

>>> student_tuples = [
    ('john', 'A', 15),
    ('jane', 'B', 12),
    ('dave', 'B', 10),
]
>>> 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),
]
>>> sorted(student_objects, key=lambda student: student.age)   # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

更多内容,可以参考https://docs.python.org/2/howto/sorting.html


( 本文完 )