zoukankan      html  css  js  c++  java
  • python 按值排序

    转自:http://www.cnpythoner.com/post/266.html,感谢分享!

    python 字典(dict)的特点就是无序的,按照键(key)来提取相应值(value),如果我们需要字典按值排序的话,那可以用下面的方法来进行:

    1 下面的是按照value的值从大到小的顺序来排序。

    dic = {'a':31, 'bc':5, 'c':3, 'asd':4, 'aa':74, 'd':0}
    dict= sorted(dic.iteritems(), key=lambda d:d[1], reverse = True)
    print dict

    输出的结果:
    [('aa', 74), ('a', 31), ('bc', 5), ('asd', 4), ('c', 3), ('d', 0)]

    返回值是元组

    取topN 的操作(取键值)

    poplist=[]
    for i in range(topN):
    poplist.append(dict[i][0])



    下面我们分解下代码
    print dic.iteritems() 得到[(键,值)]的列表。
    然后用sorted方法,通过key这个参数,指定排序是按照value,也就是第一个元素d[1的值来排序。reverse = True表示是需要翻转的,默认是从小到大,翻转的话,那就是从大到小。

    2 对字典按键(key)排序:
    dic = {'a':31, 'bc':5, 'c':3, 'asd':4, 'aa':74, 'd':0}
    dict= sorted(dic.iteritems(), key=lambda d:d[0]) d[0]表示字典的键
    print dict

  • 相关阅读:
    数组
    对象
    js继承
    js原型原型链
    es6(初级)
    canvas背景
    Angular.js进阶
    Angular.js-2入门
    angular.js-1初识
    js之广告
  • 原文地址:https://www.cnblogs.com/baiting/p/7125718.html
Copyright © 2011-2022 走看看