python sorted排序用法详解
来源:互联网 发布:域名注册手机号 编辑:程序博客网 时间:2024/04/28 17:26
sorted排序
1. operator函数
在介绍sorted函数之前需要了解一下operator函数。
operator函数是python的内置函数,提供了一系列常用的函数操作
比如,operator.mul(x, y)等于x+y
- a = [1,2,3]
- b = [5,6,7]
- c = map(operator.mul, a, b)
- # c的值就为[5, 12, 21]
这里只介绍它的itemgetter() 方法,更多的介绍可参考官网。
operator — Standard operators as functions
operator模块提供的itemgetter函数用于获取对象的哪些维的数据,参数为一些序号(即需要获取的数据在对象中的序号),下面看例子。
- a = [1,2,3]
- >>> b=operator.itemgetter(1) //定义函数b,获取对象的第1个域的值
- >>> b(a)
- 2
- >>> b=operator.itemgetter(1,0) //定义函数b,获取对象的第1个域和第0个的值
- >>> b(a)
- (2, 1)
2. sorted函数
函数介绍:Built-in Function
官网示例:Sorting HOW TO?
函数原型:sorted(iterable[, cmp[, key[, reverse]]])
Return a new sorted list from the items in iterable.(会返回一个重新排列好的list)
iterable(可迭代):可以是list也可以是dict
cmp:可以自定义比较规则,这里不详细叙述
key:用于比较的值
reverse:指定是顺序还是逆序
下面以dict排序为例做讲解:
- c = {'a': 15, 'ab': 6, 'bc': 16, 'da': 95}
-
- d = sorted(c.iteritems(),key=operator.itemgetter(0),reverse=True)
- >>> [('da', 95), ('bc', 16), ('ab', 6), ('a', 15)]
-
- e = sorted(c.iteritems(),key=operator.itemgetter(0),reverse=True)
- >>>['da', 'bc', 'a', 'ab']
1.注意区分dict加与不加iteritems() 对于结果的影响
2.我们的key选择的是传入参数的第0号元素,在这里即是键(keys),所以最终的排序是按照键排序,我们也可以以值作为标准进行排序,看下面示例
- d = sorted(c.iteritems(),key=operator.itemgetter(1),reverse=True)
- >>> [('da', 95), ('bc', 16), ('a', 15), ('ab', 6)]
看到这你会不会觉得operator的itemgetter函数可以用lambda函数实现:我们可以将上面的示例改成lambda
- d = sorted(c.iteritems(),key=lambda x:x[1],reverse=True)
- >>> [('da', 95), ('bc', 16), ('a', 15), ('ab', 6)]
你看结果是一样一样的。
文章参考:
Python中的sorted函数以及operator.itemgetter函数
python中的operator库
- python sorted排序用法详解
- python sorted排序用法详解
- python sorted()用法详解
- python sort sorted 排序详解
- python内置函数sorted排序用法
- python内置函数sorted排序用法
- python内置函数sorted排序用法
- Python-排序用法-sort、sorted、reverse、reversed
- Python教程:[66]sorted()排序详解
- Python排序函数sort()和sorted()详解
- Python中的排序函数argsort,sort,sorted用法
- Python 列表排序方法reverse、sort、sorted详解
- Python 列表排序方法reverse、sort、sorted详解
- Python 列表排序方法reverse、sort、sorted详解
- Python 列表排序方法reverse、sort、sorted详解
- Python 列表排序方法reverse、sort、sorted详解
- python 列表排序方法reverse、sort、sorted详解
- Python列表排序 reverse、sort、sorted 操作方法详解
- 微信小程序wx:for和wx:for-item的正确用法
- pyqt样式表语法笔记(中)--原创
- pyqt样式表语法笔记(下)--原创
- 【鸡汤】忘记哪儿来的故事!
- pyqt系列原创入门教程
- python sorted排序用法详解
- 常见排序算法-Python实现
- 作品集
- c++学习笔记之封装篇(上)
- deepin系统如何安装deb格式的软件
- OPENCV_图片文字_矩形_圆形_直线_图片缩放
- deepin系统下如何设置wifi热点(亲测有效)
- 括号匹配(二)
- 如何下载github项目中的部分文件(文件夹)