zoukankan      html  css  js  c++  java
  • python中列表排序,字典排序,列表中的字典排序

    python中列表排序,字典排序,列表中的字典排序

    import operator  
    一. 按字典值排序(默认为升序)  
    x = {1:2, 3:4, 4:3, 2:1, 0:0}   
    1. sorted_x = sorted(x.iteritems(), key=operator.itemgetter(1))  
    print sorted_x  
    #[(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]  
    #如果要降序排序,可以指定reverse=True  
    2. sorted_x = sorted(x.iteritems(), key=operator.itemgetter(1), reverse=True)  
    print sorted_x  
    #[(3, 4), (4, 3), (1, 2), (2, 1), (0, 0)] 
    
    二. 或者直接使用list的reverse方法将sorted_x顺序反转  
    #sorted_x.reverse()  
      
    三. 更为常用的方法是,用lambda表达式  
    3. sorted_x = sorted(x.iteritems(), key=lambda x : x[1])  
    print sorted_x  
    #[(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]  
    4. sorted_x = sorted(x.iteritems(), key=lambda x : x[1], reverse=True)  
    print sorted_x  
    #[(3, 4), (4, 3), (1, 2), (2, 1), (0, 0)]  
      
    四. 包含字典dict的列表list的排序方法与dict的排序类似,如下:  
    x = [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]  
    sorted_x = sorted(x, key=operator.itemgetter('name'))  
    print sorted_x  
    #[{'age': 10, 'name': 'Bart'}, {'age': 39, 'name': 'Homer'}]  
    sorted_x = sorted(x, key=operator.itemgetter('name'), reverse=True)  
    print sorted_x  
    #[{'age': 39, 'name': 'Homer'}, {'age': 10, 'name': 'Bart'}]  
    sorted_x = sorted(x, key=lambda x : x['name'])  
    print sorted_x  
    #[{'age': 10, 'name': 'Bart'}, {'age': 39, 'name': 'Homer'}]  
    5. sorted_x = sorted(x, key=lambda x : x['name'], reverse=True)  
    print sorted_x  
    #[{'age': 39, 'name': 'Homer'}, {'age': 10, 'name': 'Bart'}] 
    
  • 相关阅读:
    MySQL中文显示乱码
    mysql 存储引擎 InnoDB 与 MyISAM 的区别和选择
    mysql 分表的3种方法
    mysql 清空或删除表数据后,控制表自增列值的方法
    MySQL 下优化SQL语句的一些经验
    mysql 常用命令
    MySQL获得指定数据表中auto_increment自增id值的方法及实例
    SQL Server Alwayson创建代理作业注意事项
    LinkedList子类与Queue接口
    List接口
  • 原文地址:https://www.cnblogs.com/whkzm/p/14072063.html
Copyright © 2011-2022 走看看