• 技术文章 >Python技术 >Python高级

    python itemgetter函数实现字典排序

    小妮浅浅小妮浅浅2021-04-09 09:54:37原创3343

    本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

    1、Itemgetter概念

    用于获取对象的哪些位置的数据,参数即为代表位置的序号值

    2、使用方法

    from operator import itemgetter

    import operator

    调用时需要用operator.itemgetter

    3、注意点

    operator.itemgetter函数获取的不是值,而是定义了一个函数,通过该函数作用到对象上才能获取值。

    4、实例

    通过使用 operator 模块的 itemgetter 函数,可以非常容易的排序数据结构,代码如下:

    In [46]: from operator import itemgetter
     
    In [47]: rows_by_fname = sorted(rows, key=itemgetter('fname'))
     
    In [48]: rows_by_fname
    Out[48]:
    [{'fname': 'Big', 'lname': 'Jones', 'uid': 1004},
     {'fname': 'Brian', 'lname': 'Jones', 'uid': 1003},
     {'fname': 'David', 'lname': 'Beazley', 'uid': 1002},
     {'fname': 'John', 'lname': 'Cleese', 'uid': 1001}]
     
    In [49]: rows_by_uid = sorted(rows, key=itemgetter('uid'))
     
    In [50]: rows_by_uid
    Out[50]:
    [{'fname': 'John', 'lname': 'Cleese', 'uid': 1001},
     {'fname': 'David', 'lname': 'Beazley', 'uid': 1002},
     {'fname': 'Brian', 'lname': 'Jones', 'uid': 1003},
     {'fname': 'Big', 'lname': 'Jones', 'uid': 1004}]

    在对于字典的排序上,我们已经学过了不少的方法,本篇要带来的是operator 模块中Itemgetter函数的方法。它可以就字典中的某个字段进行排序,最后我们得到的结果也更加有针对性。

    以上就是python itemgetter函数实现字典排序的方法,大家在正式开始操作之前,需要对itemgetter函数的基本内容有所了解,这样才能更好的结合字典进行使用更多Python高级指路:python高级

    专题推荐:python itemgetter
    品易云
    上一篇:numpy.append()中axis三种用法介绍 下一篇:python3函数有哪些高级特性?

    相关文章推荐

    • python中使用__slots__定义类属性• defaultdict在python中计算键值的和• python sorted对键和值进行排序

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网