operator.itemgetter() 字典列表排序】的更多相关文章

## 字典列表排序 students = [ {"name": "Stanley", "age": 22, "score": 92}, {"name": "Peter", "age": 19, "score": 99}, {"name": "Well", "age": 23, "…
举例: import operator 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'}] 倒序输出:只需要加1个…
问题:想根据一个或多个字典中的值来对列表排序 解决方案:利用operator模块中的itemgetter()函数对这类结构进行排序是非常简单的. # Sort a list of a dicts on a common key rows = [ {'fname': 'Brian', 'lname': 'Jones', 'uid': 1003}, {'fname': 'David', 'lname': 'Beazley', 'uid': 1002}, {'fname': 'John', 'lnam…
记录一下昨天学到的知识: 一.文件相关 文件追加:f = open("fname","a")    文件不存在时创建 二.时间戳相关 http://www.jb51.net/article/47957.htm 获取时间戳: import time #获得当前时间时间戳 now = int(time.time()) 获取指定格式时间: import datetime #获得当前时间 now = datetime.datetime.now() ->这是时间数组格式…
operator.itemgetter函数 operator模块提供的itemgetter函数用于获取对象的哪些维的数据,参数为一些序号(即需要获取的数据在对象中的序号),要注意,operator.itemgetter函数获取的不是值,而是定义了一个函数,通过该函数作用到对象上才能获取值. eg:  students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]  sorted(students, key=lambda s…
itemgetter函数:对字典列表进行多键排序 from operator import itemgetter list_people = [ {'name': 'Mike', 'age': 22, 'score': 90}, {'name': 'Alice', 'age': 22, 'score': 90}, {'name': 'Lee', 'age': 26, 'score': 92}, {'name': 'Ben', 'age': 26, 'score': 85}, {'name': '…
Python3 中的排序,在 Sorting HOW TO 中已经讲得很清楚了.来个实际的例子,对下面的这个 list 依据创建时间排序: pages = [{'title': '十年学会程序设计', 'time': '2012-02-14', 'name': '21-days'}, {'title': 'ANE Toolkit', 'time': '2012-06-07', 'name': 'anetoolkit'}, {'title': 'cocos2d-x-filters', 'time'…
#-*- encoding=utf-8 -*- # python3代码 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. s…
https://blog.csdn.net/ray_up/article/details/42084863 一: 字典排序 解析: 使用sorted 方法, 排序后的结果为一个元组. 可以字符串排序(那数字肯定更没问题了!) 1:  按照键值(value)排序 a = {'a': 'China', 'c': 'USA', 'b': 'Russia', 'd': 'Canada'}b = sorted(a.items(), key=lambda x: x[1], reverse=True)结果:[…
在程序中使用字典进行数据信息统计时,由于字典是无序的所以打印字典时内容也是无序的.因此,为了使统计得到的结果更方便查看需要进行排序.Python中字典的排序分为按“键”排序和按“值”排序. 1.按“值”排序 按“值”排序就是根据字典的值进行排序,可以使用内置的sorted()函数. sorted(iterable[, cmp[, key[, reverse]]]) (1)iterable:是可迭代类型类型; (2)cmp:用于比较的函数,比较什么由key决定,有默认值,迭代集合中的一项; (3)…