python排序详解

2018-03-02  本文已影响0人  AllenDown

震惊,Python竟然如此排序

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

1.列表排序

In [1]: a = [5, 3, 2, 1, 4]
In [2]: a.sort()
In [3]: a
Out[3]: [1, 2, 3, 4, 5]

:排序后原list已经改变

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.字典排序

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)]

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

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)]
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
上一篇下一篇

猜你喜欢

热点阅读