python itemgetter函数实现字典排序

679次阅读
没有评论

python

python itemgetter函数实现字典排序

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函数的基本内容有所了解,这样才能更好的结合字典进行使用。

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2021-07-14发表,共计1061字。
新手QQ群:570568346,欢迎进群讨论 Python51学习