python学习 -- operator.itemgetter(), list.sort/sorted 以及lambda函数

Python 中有非常方便高效的排序函数,下面主要介绍如何sort/sorted对list,dict进行排序。

1. 用list.sort /sorted 对list of tuples中第二个值进行排序

>>> import operator
>>> a=[('a',3),('b',2),('c',1)]
>>> import operator
>>> l=[('a',3),('b',2),('c',1)]
>>> l.sort(key=operator.itemgetter(1))
>>> l
[('c', 1), ('b', 2), ('a', 3)]
>>> sorted(l, key=operator.itemgetter(1))
[('c', 1), ('b', 2), ('a', 3)]
>>> sorted(l, key=operator.itemgetter(0))
[('a', 3), ('b', 2), ('c', 1)]

  list.sort 和sorted 的区别:sort是list序列的一个方法,而sorted是内建函数

  list.sort: 没有返回值,而且 sort作为序列的内部函数,调用完后会对调用的序列进行排序

  sorted:函数不改变参数,并返回排好序的序列副本

  在python开发文档中对sort和sorted都有详细介绍,也可以调用help函数来查看两者的区别

>>> help(list.sort)
Help on method_descriptor:

sort(...)
    L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*
>>> help(sorted)
Help on built-in function sorted in module builtins:

sorted(iterable, /, *, key=None, reverse=False)
    Return a new list containing all items from the iterable in ascending order.

    A custom key function can be supplied to customize the sort order, and the
    reverse flag can be set to request the result in descending order.

 

2. 除了用operator之外我们也可以用lambda

>>> l.sort(key=lambda x:x[1])
>>> l
[('c', 1), ('b', 2), ('a', 3)]

 

3. 用sorted来对ditionary进行排序

>>> l = {'a': 3,"b": 2,"c": 1}
>>> sl_key = sorted(l.items())  #Sort by key
>>> sl_key
[('a', 3), ('b', 2), ('c', 1)]
>>> sl_value = sorted(l.items(),key=lambda x:x[1])  #Sort by value
>>> sl_value
[('c', 1), ('b', 2), ('a', 3)]
>>> sl_value = sorted(l.items(),key=lambda x:x[1], 
reverse=True)  #Sort by value Backwards
>>> sl_value
[('a', 3), ('b', 2), ('c', 1)]
>>> sl_value = sorted(l.items(),key=lambda x:(x[1],x[0]),
reverse=True)  #Sort by value then by Key
>>> sl_value
[('a', 3), ('b', 2), ('c', 1)]

  

posted @ 2018-01-21 03:27  老张哈哈哈  阅读(475)  评论(0编辑  收藏  举报