zoukankan      html  css  js  c++  java
  • python 列表及字典(按key、按value排序)

    python dict按照key 排序:

    1、method 1.

    items = dict.items()
    items.sort()
    for key,value in items:
       print key, value # print key,dict[key]
    

    2、method 2.

    print key, dict[key] for key in sorted(dict.keys())
    

     

    python dict按照value排序:

    method 1:

    把dictionary中的元素分离出来放到一个list中,对list排序,从而间接实现对dictionary的排序。这个“元素”可以是key,value或者item。

    method2:

    #用lambda表达式来排序,更灵活:
    sorted(dict.items(), lambda x, y: cmp(x[1], y[1]))
    #降序
    sorted(dict.items(), lambda x, y: cmp(x[1], y[1]), reverse=True)
    

    下面给出python内置sorted函数的帮助文档:

    sorted(...)
    sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list

    python list排序:

    list有sort方法:

      如:
       >>> s=[2,1,3,0]
       >>> s.sort()
       [0, 1, 2, 3]

  • 相关阅读:
    ubuntu上安装boost库
    boost array使用
    2017新年总结
    qt 设置等待事件
    vs下 qt源码调试
    使用记事本创建Web服务(WebService)
    司以类聚,人以群分
    附件上传
    DES 加密解密
    工作总结-js插件
  • 原文地址:https://www.cnblogs.com/changxiaoxiao/p/3077546.html
Copyright © 2011-2022 走看看