美文网首页
python排序详解

python排序详解

作者: AllenDown | 来源:发表于2018-03-02 13:48 被阅读0次

    震惊,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

    相关文章

      网友评论

          本文标题:python排序详解

          本文链接:https://www.haomeiwen.com/subject/kwlaxftx.html