Python笔记精讲之排序--sorted()

排序:

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']
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值