from operator import itemgetter
from operator import attrgetter
rows = [
{'fname': 'Brian', 'lname': 'Jones', 'uid': 1003},
{'fname': 'David', 'lname': 'Beazley', 'uid': 1002},
{'fname': 'John', 'lname': 'Cleese', 'uid': 1001},
{'fname': 'Big', 'lname': 'Jones', 'uid': 1004}
]
# 按照uid倒序
print(sorted(rows, key=lambda r: r['uid'], reverse=True))
# 使用 itemgetter() 方式会运行的稍微快点
print(sorted(rows, key=itemgetter('uid'), reverse=True))
print(sorted(rows, key=itemgetter('fname', 'lname')))
print(sorted(rows, key=lambda r: (r['fname'], r['lname'])))
class User:
def __init__(self, user_id):
self.user_id = user_id
def __repr__(self):
return 'User({})'.format(self.user_id)
users = [User(23), User(2), User(4)]
print(sorted(users, key=lambda u: u.user_id))
print(sorted(users, key=attrgetter('user_id')))