python——使用itemgetter和sorted对列表内的元素进行排序
来源:互联网 发布:号码归属地软件下载 编辑:程序博客网 时间:2024/05/20 19:22
参考文章http://www.cnblogs.com/100thMountain/p/4719503.html
这几日胡哥在旁边疯狂阅读deep walk之类的算法和论文,下了包之后研究源码。突然喊我:诶,kf,你看这个。
我一看,是以前没用过的itemgetter,于是百度了一。
itemgetter和sorted很适合于列表循环,比如下面的场景:
score = [('A',80),('B',82),('C',70)]
现在要按列表里各元祖的第二位排序,怎么排?
其实使用sorted函数+itemgetter可以很容易实现。
sorted(score, key=operator.itemgetter(1))
结果是[('C', 70), ('A', 80), ('B', 82)],很方便吧。
大家应该知道,python还有一个sort函数,那么sort函数和sorted函数有什么呢?
sort()是可变对象(字典、列表)的方法,不需要参数,并且没有返回值(sort()会改变可变对象,因此无需返回值);而sorted()是python的内置函数,并不是可变对象(列表、字典)的特有方法,sorted()函数需要一个参数(参数可以是列表、字典、元组、字符串),无论传递什么参数,都将返回一个以列表为容器的返回值,如果是字典将返回键的列表。简单来说,如果一个列表a = [2,9,4,8],使用sort()函数,a本身就被修改了。而使用sorted(a),就需要赋值给新的变量。
而itemgetter是Operator 模块函数。看一下它的使用方法:
f = itemgetter(1)
a = [1,2,3]
f(a)
输出是2,你发现f像什么?像一个函数。其实operator.itemgetter函数获取的不是值,而是定义了一个函数,通过该函数作用到对象上才能获取值。
所以现在再看sorted(score, key=operator.itemgetter(1))你就能看懂了吧。
- python——使用itemgetter和sorted对列表内的元素进行排序
- python sorted函数(结合使用lambda和operator.itemgetter()来对字典进行排序)
- Python sorted对字典和列表进行排序
- itemgetter对列表排序
- itemgetter对列表排序
- python——sorted函数、sort函数以及operator.itemgetter的使用
- 使用sorted对列表和字典 排序
- python3使用operator.itemgetter对字典进行排序
- python排序sorted()与operator.itemgetter()函数
- python学习——采用sorted方法对字典的键、值进行排序
- Python中的itemgetter和sorted函数
- python中的sorted、iteritems和operator.itemgetter
- Python-sorted函数和operator.itemgetter函数
- Python: sorted,operator.itemgetter的用法
- python iteritems(),itemgetter(),sorted()
- python sorted operator.itemgetter
- python iteritems() itemgetter() sorted()
- Python使用collections的Counter类对字符串、列表、字典的数据元素进行计数
- 前端学习笔记2-3 CSS
- 时间复杂度
- kettle5.3扩展step插件支持元数据注入
- Android多线程异步任务,在主线程中回调
- Kafka+Log4j实现日志集中管理
- python——使用itemgetter和sorted对列表内的元素进行排序
- Unity常用插件
- 九度OJ-题目1165:字符串匹配
- 一个例子让你彻底明白原型对象和原型链
- C语言函数itoa() 和atoi() 详解
- CSDN日报20170629——《你该关注“硬技术”还是“大道理”呢?》
- Activity的启动模式和标记位
- Python re 模块
- (1)clock source(时钟源)