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 降序
    

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


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

  • 相关阅读:
    struts2知识系统整理
    JavaScript onload
    百度云如何为用户分配内存空间
    集合运算
    [hdu3530]单调队列
    [hdu4911]逆序对相关
    [hdu5199]统计数据的水题
    [hdu5200]离线+标记
    [hdu5204]水题
    [hdu5203]计数水题
  • 原文地址:https://www.cnblogs.com/Renqy/p/12786603.html
Copyright © 2011-2022 走看看