排序:
1)使用key来指定排序顺序,先按照姓名升序排序,姓名相同的按年龄降序排序
>>> persons=[{'name':'Dong','age':14},{'name':'Zhang','age':8},{'name':'Liu','age':18},{'name':'Wang','age':8}]
>>> persons.append({'name':'Zhang','age':28})
>>> persons
[{'name': 'Dong', 'age': 14}, {'name': 'Zhang', 'age': 8}, {'name': 'Liu', 'age': 18}, {'name': 'Wang', 'age': 8}, {'name': 'Zhang', 'age': 28}]
>>> print(sorted(persons,key=lambda x:(x['name'],-x['age'])))
[{'name': 'Dong', 'age': 14}, {'name': 'Liu', 'age': 18}, {'name': 'Wang', 'age': 8}, {'name': 'Zhang', 'age': 28}, {'name': 'Zhang', 'age': 8}]
2)字典排序
>>> phonebook={'Linda':'7750','Bob':'9345','Carol':'5834'}
>>> from operator import itemgetter
>>> sorted(phonebook.items(),key=itemgetter(1)) #按字典中元素值排序
[('Carol', '5834'), ('Linda', '7750'), ('Bob', '9345')]
>>> sorted(phonebook.items(),key=itemgetter(0)) #按字典中元素键排序
[('Bob', '9345'), ('Carol', '5834'), ('Linda', '7750')]
>>> gamend=[{'name':'Bob','wins':10,'losses':3,'rating':78},
... {'name':'David','wins':3,'losses':5,'rating':56},
... {'name':'Patty','wins':9,'losses':9,'rating':76}]
>>> sorted(gamend,key=itemgetter('wins','name')) #按‘wins’升序,该值相同按‘name’升序排序
[{'name': 'David', 'wins': 3, 'losses': 5, 'rating': 56}, {'name': 'Patty', 'wins': 9, 'losses': 9, 'rating': 76}, {'name': 'Bob', 'wins': 10, 'losses': 3, 'rating': 78}]
3)列表排序
>>> gameresult=[['Bob',95,'A'],['Alan',86,'C'],['Mandy',83.5,'A'],['Rob',89.3,'E']]
>>> sorted(gameresult,key=itemgetter(0,1)) #按姓名升序排序,姓名相同按分数升序排序
[['Alan', 86, 'C'], ['Bob', 95, 'A'], ['Mandy', 83.5, 'A'], ['Rob', 89.3, 'E']]
>>> gameresult.append(['Jay',95,'A'])
>>> sorted(gameresult,key=itemgetter(1,0)) #按分数升序排序,分数相同按姓名升序排序
[['Mandy', 83.5, 'A'], ['Alan', 86, 'C'], ['Rob', 89.3, 'E'], ['Bob', 95, 'A'], ['Jay', 95, 'A']]
>>> sorted(gameresult,key=itemgetter(2,0)) #按等级升序,等级相同按姓名升序
[['Bob', 95, 'A'], ['Jay', 95, 'A'], ['Mandy', 83.5, 'A'], ['Alan', 86, 'C'], ['Rob', 89.3, 'E']]
4)根据另外一个列表的值来对当前列表元素排序
>>> list1=["what","I'm","sorting","by"]
>>> list2=["something","else","to","sort"]
>>> pairs=zip(list1,list2)
>>> pairs=sorted(pairs)
>>> pairs
[("I'm", 'else'), ('by', 'sort'), ('sorting', 'to'), ('what', 'something')]
>>> result=[x[1] for x in pairs]
>>> result
['else', 'sort', 'to', 'someting']