zoukankan      html  css  js  c++  java
  • 字典排序问题

    2018-01-03@望京

    排序,立即想到用Python的内置函数sorted()

    Python 2.x 中
    sorted(...)
        sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list
    
    
    Python 3.x 中
    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 customise the sort order, and the
        reverse flag can be set to request the result in descending order.
    

    字典按key排序

    >>> dic = {'a':9, 'c':3, 'f':12, 'b':1, 'd':7}
    >>> 
    >>> sorted(dic)
    ['a', 'b', 'c', 'd', 'f']
    >>> 
    >>> sorted(dic.keys())
    ['a', 'b', 'c', 'd', 'f']
    >>> 
    >>> sorted(dic.values())
    [1, 3, 7, 9, 12]
    >>> 
    >>> sorted(dic.items())
    [('a', 9), ('b', 1), ('c', 3), ('d', 7), ('f', 12)]
    >>>
    >>> for k in sorted(dic):
    ...     print dic[k]
    ... 
    9
    1
    3
    7
    12
    >>>
    

    字典是无序的,对字典排序本身是一个没有太大意义的事,但是面试的时候总会遇到==''

    那么问题来了,如何对字典按照value排序呢(默认是对key进行排序)?

    首先需要知道sorted()这个函数的几个参数的意思(按照Python 3.x来说明):

        - iterable   指的是可迭代对象,可以是dic,dic.items(), dic.keys(),  dic.values() 等等;

        - key         key对应一个函数,用来选取参与比较的元素;

        - reverse   排序规则. reverse = True 或者 reverse = False(默认值);

    Py2中使用sort的cmp参数自定义排序方式

    >>> 
    >>> res = [{'name':'hi','age':10},{'name':None,'age':10},{'name':'bo','age':10},{'name':'aaa','age':10}]
    >>> 
    >>> res.sort(cmp=lambda x, y: cmp(x['name'], y['name']))
    >>> 
    >>> res
    [{'age': 10, 'name': None}, {'age': 10, 'name': 'aaa'}, {'age': 10, 'name': 'bo'}, {'age': 10, 'name': 'hi'}]
    >>> 

    使用key参数来实现

    items()方法将字典的元素 转化为了元组

    >>> dic
    {'a': 9, 'c': 3, 'b': 1, 'd': 7, 'f': 12}
    >>> dic.items()
    [('a', 9), ('c', 3), ('b', 1), ('d', 7), ('f', 12)]
    >>> 
    >>> sorted(dic.items())
    [('a', 9), ('b', 1), ('c', 3), ('d', 7), ('f', 12)]
    >>> 
    >>> sorted(dic.items(), key=lambda x:x[1])
    [('b', 1), ('c', 3), ('d', 7), ('a', 9), ('f', 12)]
    >>> 

    使用zip来实现

    >>> dic
    {'a': 9, 'c': 3, 'b': 1, 'd': 7, 'f': 12}
    >>> 
    >>> new_dic = zip(dic.values(), dic.keys())
    >>> 
    >>> new_dic
    [(9, 'a'), (3, 'c'), (1, 'b'), (7, 'd'), (12, 'f')]
    >>> 
    >>> sorted(new_dic)
    [(1, 'b'), (3, 'c'), (7, 'd'), (9, 'a'), (12, 'f')]
    >>> 
    

      

    作者:Standby一生热爱名山大川、草原沙漠,还有妹子
    出处:http://www.cnblogs.com/standby/

    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

  • 相关阅读:
    微信开发创建公众号或小程序菜单45064: no permission to use weapp in menu rid:XXXXXXX
    大文件上传:秒传、断点续传、分片上传
    Linux 给文件夹或者文件增加权限
    常见的架构方式
    RabbitMQ集群
    常见的系统架构思想
    RabbitMQ问题分析
    RabbitMQ实战&管理界面
    Linux安装RabbitMQ
    Redis发布订阅及消息阻塞
  • 原文地址:https://www.cnblogs.com/standby/p/8269276.html
Copyright © 2011-2022 走看看