zoukankan      html  css  js  c++  java
  • python dic字典排序

    使用lambda匿名函数来实现。

    >>> dic1 = {'a':1,'b':2,'e':5,'d':4,'c':3}
    >>> result = sorted(dic1.items(), key = lambda x :(x[1]))
    >>> result
    [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]
    >>> result = sorted(dic1.items(), key = lambda x :(-x[1]))
    >>> result
    [('e', 5), ('d', 4), ('c', 3), ('b', 2), ('a', 1)]
    >>> dic1
    {'a': 1, 'b': 2, 'e': 5, 'd': 4, 'c': 3}
    >>> result = sorted(dic1.items(), key = lambda x :(x[0]))
    >>> result
    [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]
    >>> result = sorted(dic1.items(), key = lambda x :(x[0]),reverse = True)
    >>> result
    [('e', 5), ('d', 4), ('c', 3), ('b', 2), ('a', 1)]
    
    #x[0] 用字典的第一位排序
    #x[1] 用字典的第二位排序
    #-x[0] 用第一位的负数排序
    
    默认是升序
    reverse = True 降序
    

    这个用的比较多,先记录一下。写给自己看。


    读书和健身总有一个在路上

  • 相关阅读:
    写Log日志的方法 减少插件引用
    操作文件常用的方法
    Git常用命令
    JS
    js
    BUG++
    mysql点滴记录 二 (MySql经典练习题)
    mysql点滴记录 一 (创建表结构 & 构建测试数据)
    TCPDF
    Docker-命令
  • 原文地址:https://www.cnblogs.com/Renqy/p/12786603.html
Copyright © 2011-2022 走看看