Python排序详解

震惊,Python竟然如此排序

为图方便,以下代码均在ipython中操作

1.列表排序

  • 使用sort()进行排序:
In [1]: a = [5, 3, 2, 1, 4]
In [2]: a.sort()
In [3]: a
Out[3]: [1, 2, 3, 4, 5]

:排序后原list已经改变

  • 使用sorted()进行排序:
In [4]: a = [5, 3, 2, 1, 4]
In [5]: b = sorted(a)
In [6]: b
Out[6]: [1, 2, 3, 4, 5]
In [7]: a
Out[7]: [5, 3, 2, 1, 4]

:排序后原list没有改变


2.字典排序

  • 使用sorted进行排序:
In [8]: dict = {'micheal': 23, 'kobe': 8, 'lebron': 5}
In [11]: sorted_dict = sorted(dict.items(), key=lambda x:x[0])
In [12]: sorted_dict
Out[12]: [('kobe', 8), ('lebron', 5), ('micheal', 23)]
In [13]: sorted_dict2 = sorted(dict.items(), key=lambda x:x[1])
In [14]: sorted_dict2
Out[14]: [('lebron', 5), ('kobe', 8), ('micheal', 23)]

:将dict.items()传给sorted函数,一个匿名函数传递给sorted可选参数key,当匿名函数返回x[0]时,sorted对字典的key进行排序,返回x[1]时,则对字典的value进行排序,事实上,dict.items()就是将字典转化成一组tuple的list,如下:

In [10]: dict.items()
Out[10]: dict_items([('kobe', 8), ('micheal', 23), ('lebron', 5)])

3.对象排序

  • 和字典排序方法基本一样,代码如下:
In [3]: class Player:
   ...:     def __init__(self, name, level, num):
   ...:         self.name = name
   ...:         self.level = level
   ...:         self.num = num
   ...:     def __repr__(self):
   ...:         return repr((self.name, self.level, self.num))
   ...: players = [Player('kobe', 'S', 8), Player('micheal', 'A', 23), Player('lebron', 'B', 5)]
   ...: sorted_players = sorted(players, key=lambda player:player.num)
   ...: sorted_players
Out[3]: [('lebron', 'B', 5), ('kobe', 'S', 8), ('micheal', 'A', 23)]

:在匿名函数中指定按对象哪个属性排序

  • 特别地,可以使用oprator模块中的itemgetterattrgetter先后根据对象的多个属性进行排序,如以下代码所示,分别将函数itemgetterattrgetter函数传递给参数key即可对对象进行排序,区别是:

  • attrgetter接收对象属性名参数,如下:

In [5]: from operator import itemgetter, attrgetter
In [6]: players = [Player('kobe', 'S', 8), Player('micheal', 'S', 5), Player('lebron', 'B', 5)]
In [7]: sorted_players = sorted(players, key=attrgetter('level', 'num'))
In [8]: sorted_players
Out[9]: [('lebron', 'B', 5), ('micheal', 'S', 5), ('kobe', 'S', 8)]
  • itemgetter接收int型参数,如下:
In [10]: players = [('kobe', 'S', 58), ('micheal', 'S', 5), ('lebron', 'B', 5)]
In [11]: sorted_players = sorted(players, key=itemgetter(1, 2))
In [12]: sorted_players
Out[13]: [('lebron', 'B', 5), ('micheal', 'S', 5), ('kobe', 'S', 58)]

代码中的彩蛋
god of bascketball

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值