zoukankan      html  css  js  c++  java
  • Python-如何对字典集合进行排序

    一: 通过lambda表达式来指定排序字段

    salaries = [{'Alice': 100000, 'Bob': 24000},
                {'Alice': 121000, 'Bob': 48000},
                {'Alice': 12000, 'Bob': 66000}]
    
    Use the sorted() function with key argument to create a new dic.
    sorted_salaries = sorted(salaries, key=lambda d: d['Alice'])
    
    print(sorted_salaries)
    

    二:使用集合遍历器(Itemgetter)来指定排序字段

    from operator import itemgetter
    
    salaries = [{'Alice': 100000, 'Bob': 24000},
                {'Alice': 121000, 'Bob': 48000},
                {'Alice': 12000, 'Bob': 66000}]
    
    sorted_salaries = sorted(salaries, key=itemgetter('Alice'))
    print(sorted_salaries)
    

    三:指定多个排序字段

    db = [{'username': 'Alice', 'joined': 2020, 'age': 23},
          {'username': 'Bob', 'joined': 2018, 'age': 19},
          {'username': 'Alice', 'joined': 2020, 'age': 31}]
    db_sorted = sorted(db, key=lambda row: (row['username'],
                                            row['joined'],
                                            row['age']))
    
    print(db_sorted)
    

    四:指定升序or降序

    db = [{'username': 'Alice', 'joined': '2019-03-02', 'age': 23},
          {'username': 'Bob', 'joined': '2020-08-08', 'age': 19},
          {'username': 'Alice', 'joined': '2019-03-04', 'age': 31}]
    
    db_sorted = sorted(db, key=lambda row: row['joined'], reverse=True)
    print(db_sorted)
    

    或者
    db_sorted = sorted(db, key=lambda row: row['joined'])[::-1]

  • 相关阅读:
    设计模式之工厂模式
    在线预览插件pdf.js使用记录
    自学Python:自定义模块导入问题
    MVC流程
    关于django的一些基础知识
    day72 关于rbac组件的小部分面试题
    linux的简单操作和安装
    day71 菜单的排序 点击被选中
    day063 form 和modelform组件
    day051 django第二天 django初识代码
  • 原文地址:https://www.cnblogs.com/airven/p/14250400.html
Copyright © 2011-2022 走看看