# python排序sort()与sorted()

1.按照字母表输出一个序列

2.对记录的多个字段排序等

sort()

sorted()

1.sorted()应用范围更广

sorted(iterable[, cmp[, key[, reverse]]])

s.sorted([cmp[, key[, reverse]]])

>>> persons = [{‘name’:’jon’,’age’: 32}, {‘name’:’alan’,’age’: 50}, {‘name’: ‘bob’, ‘age’:23}]>>> sorted(persons, key=lambda x: (x[‘name’], -x[‘age’]))[{‘age’: 50, ‘name’: ‘alan’}, {‘age’: 23, ‘name’: ‘bob’}, {‘age’: 32, ‘name’: ‘jon’}]

sorted()可用于任意可迭代对象，sort()一般作用于列表

>>> a = (1,2,4,2,3)>>> a.sort()traceback (most recent call last): file “”, line 1, in attributeerror: ‘tuple’ object has no attribute ‘sort’>>> sorted(a)[1, 2, 2, 3, 4]

2.sorted()返回排序后的列表，原列表不变，sort()直接修改原有列表。

sort()因为不需要复制原有列表，消耗内存少，效率高

>>> a=[‘1′,1,’a’,3,7,’n’]>>> sorted(a)[1, 3, 7, ‘1’, ‘a’, ‘n’]>>> a[‘1’, 1, ‘a’, 3, 7, ‘n’]>>> a.sort()>>> a[1, 3, 7, ‘1’, ‘a’, ‘n’]

3.对于sort()和sorted()函数，传入参数key比参数cmp效率高。cmp传入的函数在整个排序过程中多次调用，开销大；key针对每个元素仅作一次处理。

>>> from timeit import timer>>> timer(stmt=”sorted(xs,key=lambda x:x[1])”,setup=”xs=range(100);xs=zip(xs,xs);”).timeit(10000)0.35391712188720703>>> timer(stmt=”sorted(xs,cmp=lambda a,b: cmp(a[1],b[1]))”,setup=”xs=range(100);xs=zip(xs,xs);”).timeit(10000)0.4931659698486328

4.sorted()可以对多种数据结构排序

>>> phonebook = {‘linda’:’7750′,’bob’:’9345′,’carol’:’5834′}>>> from operator import itemgetter>>> sorted_pb = sorted(phonebook.iteritems(),key=itemgetter(1))>>> sorted_pb[(‘carol’, ‘5834’), (‘linda’, ‘7750’), (‘bob’, ‘9345’)]

>>> from operator import itemgetter>>> gameresult = [[‘bob’,95.00,’a’],[‘alan’,86.0,’c’],[‘mandy’,82.5,’a’],[‘rob’,86,’e’]]>>> sorted(gameresult, key=itemgetter(2, 1))[[‘mandy’, 82.5, ‘a’], [‘bob’, 95.0, ‘a’], [‘alan’, 86.0, ‘c’], [‘rob’, 86, ‘e’]]

>>> mydict = {‘li’:[‘m’,7],… ‘zhang’: [‘e’,2],… ‘wang’:[‘p’,3],… ‘du’:[‘c’,2]}>>> from operator import itemgetter>>> sorted(mydict.iteritems(),key=lambda(k,v):operator.itemgetter(1)(v))[(‘zhang’, [‘e’, 2]), (‘du’, [‘c’, 2]), (‘wang’, [‘p’, 3]), (‘li’, [‘m’, 7])]

list中混合字典：

>>> gameresult = [{“name”:”bob”,”wins”:10,”losses”:3,”rating”:75.00},… {“name”:”david”,”wins”:3,”loses”:5,”rating”:57.00}]>>> from operator import itemgetter>>> sorted(gameresult,key=itemgetter(“rating”,”name”))[{‘wins’: 3, ‘rating’: 57.0, ‘name’: ‘david’, ‘loses’: 5}, {‘wins’: 10, ‘losses’: 3, ‘name’: ‘bob’, ‘rating’: 75.0}]>>>

Posted in 未分类