自带函数
listdata.sort(cmp=None, key=None, reverse=False) # just for list, inplace-sort
sorted(iterable, cmp=None, key=None, reverse=False) # iterable object, new place
self-defined-cmp
def selfcmp(x, y):
if x > y:
return 1
elif x < y:
return -1
else:
return 0
from functools import cmp_to_key # trans selfcmp to keyfunc
sorted(hashmap.items(), key=cmp_to_key(selfcmp))
lambda
sorted(hashmap.items(), key=lambda x: x[1], reverse=False)
operator.itemgetter
# sort the iterable object by multi-keys
import operator
data = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
result = sorted(data, key=operator.itemgetter(1,2)) # [('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]