# python排序函数sorted用法分析

1.对自定义的对象进行较复杂的条件排序，比如按姓名排序，按成绩排序，先按成绩若成绩相等再按姓名排序等多种排序方式用法举例。

```from operator import attrgetter
from operator import itemgetter

#自定义复杂对象排序
class Node(object):
def __init__(self, name, score):
self.name = name;
self.score = score;

#方便打印查看排序结果
def __repr__(self):
return '(name={}, score={})'.format(self.name, self.score);

a = Node('ghz', 2)
b = Node('zhh', 1)
c = Node('lkj', 2)
d = Node('lsjdf', 1)

l = [a, b, c, d]

#以score升序排列
s1 = sorted(l, key=attrgetter('score'));
print('s1:',s1)

s11 = sorted(l, key=lambda item:item.score)
print('s11:', s11)

#以score降序排列
s2 = sorted(l, key=attrgetter('score'), reverse=True);
print('s2:', s2)

s21 = sorted(l, key=lambda item:item.score, reverse=True)
print('s21:', s21)

def cmp_my(x, y):
if x.score == y.score:
if x.name < y.name:
return 1
elif x.name == y.name:
return 0
else:
return -1
return y.score - x.score

#以score降序排列，如果score相同则以name升序排列(复合排序)
s3 = sorted(l, key=cmp_to_key(cmp_my))
print('s3:',s3)```

2.对字典对象进行排序

```from operator import attrgetter
from operator import itemgetter

#按照某个关键字对一系列字典对象排序
users = [
{'name': 'Brian', 'uid': 1003},
{'name': 'David', 'uid': 1002},
{'name': 'John', 'uid': 1001},
{'name': 'Big', 'uid': 1004}
]

#以name对字典对象排序
s_name = sorted(users, key=itemgetter('name'))
print(s_name)

s_name = sorted(users, key=lambda item: item['name'])
print(s_name)

#以uid对字典对象排序
s_uid = sorted(users, key=itemgetter('uid'))
print(s_uid)

s_uid = sorted(users, key=lambda item: item['uid'])
print(s_uid)
```