# python sorted排序

``````a = [
{"time": "2012-12-12 00:00:00"},
{"time": "2012-12-14 00:00:00"},
{"time": "2012-12-16 00:00:00"},
{"time": "2012-12-18 00:00:00"},
{"time": "2012-12-16 00:00:00"},
{"time": "2012-12-17 00:00:00"},
{"time": "2012-12-10 00:00:00"},
{"time": "2012-12-11 00:00:00"},
]

b = sorted(a, key=lambda d: d['time'])

b = [
{'time': '2012-12-10 00:00:00'},
{'time': '2012-12-11 00:00:00'},
{'time': '2012-12-12 00:00:00'},
{'time': '2012-12-14 00:00:00'},
{'time': '2012-12-16 00:00:00'},
{'time': '2012-12-16 00:00:00'},
{'time': '2012-12-17 00:00:00'},
{'time': '2012-12-18 00:00:00'}
]

``````

sorted里key接受的是一个函数，排序的时候，将key接收的函数分别作用于序列的子内容，然后通过key函数返回值排序。

``````def QuickSort(L, low, high):
"""专用快排"""
i = low
j = high
if i >= j:
return L
key = L[i]
while i < j:
while i < j and L[j]["time"] >= key["time"]:
j = j - 1
L[i] = L[j]
while i < j and L[i]["time"] <= key["time"]:
i = i + 1
L[j] = L[i]
L[i] = key
QuickSort(L, low, i - 1)
QuickSort(L, j + 1, high)
return L[::-1]
``````
``````def fun(a, b):
if a["time"] > b["time"]:
return -1
else:
return 1

c=sorted(a, cmp=fun)

c=[
{'time': '2012-12-18 00:00:00'},
{'time': '2012-12-17 00:00:00'},
{'time': '2012-12-16 00:00:00'},
{'time': '2012-12-16 00:00:00'},
{'time': '2012-12-14 00:00:00'},
{'time': '2012-12-12 00:00:00'},
{'time': '2012-12-11 00:00:00'},
{'time': '2012-12-10 00:00:00'}
]
``````

`c=sorted(a, cmp=fun)`意思是遍历a列表的时候，分别取相邻的两个数带入fun函数中 如果fun函数返回的是正数，则交换相邻的两个数据，反之，不交换

sorted还有个reverse参数，表示是否逆序，默认为reverse=False 升序排列。

sort方法也一样有这些功能