zoukankan      html  css  js  c++  java
  • 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)]
    

      

  • 相关阅读:
    android studio快捷键大全
    HTML5规范尘埃落定,5个开发工具推荐
    javascript:设置URL参数的方法,适合多条件查询
    MyBatis 多表联合查询及优化
    js动态向页面中添加表格
    mysql装完电脑里面没mysql相关服务
    javascript 实现一个网页,然后计算出有多少剩余时间的倒计时程序
    xcode于Archive当产生安装包遇到ld: library not found for -lPods
    计算机网络 2. 应用层
    Android手游《》斗地主完整的源代码(支持单机和网络对战)
  • 原文地址:https://www.cnblogs.com/laozhanghahaha/p/8322849.html
Copyright © 2011-2022 走看看