# sorted

## 排序算法

Python内置的`sorted()`函数就可以对list进行排序：

``````>>> sorted([36, 5, -12, 9, -21])
[-21, -12, 5, 9, 36]
``````

``````>>> sorted([36, 5, -12, 9, -21], key=abs)
[5, 9, -12, -21, 36]
``````

key指定的函数将作用于list的每一个元素上，并根据key函数返回的结果进行排序。对比原始的list和经过`key=abs`处理过的list：

``````list = [36, 5, -12, 9, -21]

keys = [36, 5,  12, 9,  21]
``````

``````keys排序结果 => [5, 9,  12,  21, 36]
|  |    |    |   |

``````

``````>>> sorted(['bob', 'about', 'Zoo', 'Credit'])
``````

``````>>> sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower)
``````

``````>>> sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True)
``````

## 小结

`sorted()`也是一个高阶函数。用`sorted()`排序的关键在于实现一个映射函数。

## 练习

``````L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
``````

``````# -*- coding: utf-8 -*-

L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]

def by_name(t):

pass

L2 = sorted(L, key=by_name)
print(L2)
``````

``````# -*- coding: utf-8 -*-

L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]

def by_score(t):
pass

L2 = ???

print(L2)
``````

do_sorted.py