python内置函数:sorted中的参数key
x.sort和sorted函数中参数key的使用
介绍
python中,列表自带了排序函数sort
>>> l = [1, 3, 2]
>>> l.sort()
>>> l
[1, 2, 3]
对于其他字典、元组、集合容器,可以使用内置方法sort来做排序,注意返回的结果是列表结构, 字典容器,默认是key进行排序的。
>>> # tuple sort
>>> t = (1, 3, 2)
>>> sorted(t)
[1, 2, 3]
>>>
>>> # set sort
>>> s = {1, 3, 2}
>>> sorted(s)
[1, 2, 3]
>>>
>>> # dict sort
>>> d = {1:100, 3:200, 2: 0}
>>> sorted(d)
[1, 2, 3]
>>> sorted(d.values())
[0, 100, 200]
>>> sorted(d.items())
[(1, 100), (2, 0), (3, 200)]
>>>
参数key的使用
先看一下sorted函数的文档说明
>>> help(sorted)
Help on built-in function sorted in module builtins:
sorted(iterable, /, *, key=None, reverse=False)
Return a new list containing all items from the iterable in ascending order.
A custom key function can be supplied to customize the sort order, and the
reverse flag can be set to request the result in descending order.
参数key是函数类型,用来支持自定义的排序方式。我们先看一个使用参数key的场景,比如:有一组员工工资单
| Name | salary | age |
|---|---|---|
| Tom | 4000 | 20 |
| Jerry | 4000 | 24 |
| Bob | 5000 | 28 |
希望可以按照工资从多到少排序,如果工资一样,按年龄从小到大排序
>>> salary_list = [
... ("Tom", 4000, 20),
... ("Jerry", 4000, 24),
... ("Bob", 5000, 28),
... ]
>>> # 自定义比较函数,返回值为元组(-salary, age)
>>> def mycmp(salary_item: tuple) -> (int, int):
... return (-salary_item[1], salary_item[2])
...
>>> sorted(salary_list, key=mycmp)
[('Bob', 5000, 28), ('Tom', 4000, 20), ('Jerry', 4000, 24)]
所以,为什么是这样呢?
我们来实现一个类CmpObject,在它的一些魔法方法中加入调试信息,来看看sorted函数是什么进行比较的
class CmpObject:
def __init__(self, name, val):
self.name = name
self.val = val
def __neg__(self):
print("called __neg__", self.name, self.val)
return CmpObject(self.name, -self.val)
def __eq__(self, other):
print("called __eq__")
return self.get_val() == other.get_val()
def __lt__(self, other):
print("called __lt__")
return self.get_val() < other.get_val()
def __gt__(self, other):
print("called __gt__")
return self.get_val() > other.get_val()
def get_val(self):
print("called get_val", self.name, self.val)
return self.val
def __repr__(self):
return f"{self.val}"
>>> # 初始化工资单
>>> salary_list = [
... ("Tom", CmpObject("Tom", 4000), CmpObject("Tom", 20)),
... ("Jerry", CmpObject("Jerry", 4000), CmpObject("Jerry", 24)),
... ("Bob", CmpObject("Bob", 5000), CmpObject("Bob", 28)),
... ]
>>> salary_list
[('Tom', 4000, 20), ('Jerry', 4000, 24), ('Bob', 5000, 28)]
>>> # 还是用原来的mycmp比较函数
>>> def mycmp(salary_item: tuple) -> (int, int):
... return (-salary_item[1], salary_item[2])
...
>>> # 执行排序
>>> sorted(salary_list, key=mycmp)
# 分析一下比较顺序
# sorted函数会先变量保存用于比较的key
called __neg__ Tom 4000
called __neg__ Jerry 4000
called __neg__ Bob 5000
# 新比较 -4000 -4000, 即Jerry和Tom的工资,因为是按工资倒序排(工资多的在前),所以比较的是工资的负数
called __eq__
called get_val Jerry -4000
called get_val Tom -4000
# 发现Jerry和Tom的工资相同,再去比较他们的年龄
called __eq__
called get_val Jerry 24
called get_val Tom 20
# 发现Jerry的年龄(24)大于Tom的年龄(20),Jerry要排在Tom后面
called __lt__
called get_val Jerry 24
called get_val Tom 20
# 然后比较 Bob和Jerry的工资,Bob的工资比Jerry的工资高,Jerry要排在Bob后面
called __eq__
called get_val Bob -5000
called get_val Jerry -4000
called __lt__
called get_val Bob -5000
called get_val Jerry -4000
# 又比较了 Bob和Jerry
called __eq__
called get_val Bob -5000
called get_val Jerry -4000
called __lt__
called get_val Bob -5000
called get_val Jerry -4000
# 最后比较Bob和Tom, 发现Bob的工资比Tom多,Tom要排在Bob后面
called __eq__
called get_val Bob -5000
called get_val Tom -4000
called __lt__
called get_val Bob -5000
called get_val Tom -4000
# 最后结果 Bob > Tom > Jerry
[('Bob', 5000, 28), ('Tom', 4000, 20), ('Jerry', 4000, 24)]
结论
1.sorted函数的排序策略是对于比较用的key,如果是元组形式,从左到右权重递减,(-工资, 年龄),如果-工资相同,则再比较年龄。
2.比较是用使用__eq__和__lt__进行比较,如果__eq__为真,再比较__lt__,如果__lt__为真,则要调换顺序;否则,不变。
python内置函数:sorted中的参数key的更多相关文章
- Python 内置函数sorted()在高级用法
对于Python内置函数sorted(),先拿来跟list(列表)中的成员函数list.sort()进行下对比.在本质上,list的排序和内建函数sorted的排序是差不多的,连参数都基本上是一样的. ...
- python内置函数sorted()及sort() 函数用法和区别
python内置函数sorted(),sort()都有排序的意思,但是两者有本质的区别,sort 是应用在 list 上的方法,sorted 可以对所有可迭代的对象进行排序操作,list 的 sort ...
- python 内置函数 sorted()
sorted() 函数对所有可迭代的对象进行排序操作. sort 与 sorted 区别: sort 是应用在 list 上的方法,sorted 可以对所有可迭代的对象进行排序操作. list 的 s ...
- 学习过程中遇到的python内置函数,后续遇到会继续补充进去
1.python内置函数isinstance(数字,数字类型),判断一个数字的数字类型(int,float,comple).是,返回True,否,返回False2.python内置函数id()可以查看 ...
- python内置函数
python内置函数 官方文档:点击 在这里我只列举一些常见的内置函数用法 1.abs()[求数字的绝对值] >>> abs(-13) 13 2.all() 判断所有集合元素都为真的 ...
- python 内置函数和函数装饰器
python内置函数 1.数学相关 abs(x) 取x绝对值 divmode(x,y) 取x除以y的商和余数,常用做分页,返回商和余数组成一个元组 pow(x,y[,z]) 取x的y次方 ,等同于x ...
- Python基础篇【第2篇】: Python内置函数(一)
Python内置函数 lambda lambda表达式相当于函数体为单个return语句的普通函数的匿名函数.请注意,lambda语法并没有使用return关键字.开发者可以在任何可以使用函数引用的位 ...
- 那些年,很多人没看懂的Python内置函数
Python之所以特别的简单就是因为有很多的内置函数是在你的程序"运行之前"就已经帮你运行好了,所以,可以用这个的特性简化很多的步骤.这也是让Python语言变得特别的简单的原因之 ...
- Python 内置函数笔记
其中有几个方法没怎么用过, 所以没整理到 Python内置函数 abs(a) 返回a的绝对值.该参数可以是整数或浮点数.如果参数是一个复数,则返回其大小 all(a) 如果元组.列表里面的所有元素都非 ...
- 【转】python 内置函数总结(大部分)
[转]python 内置函数总结(大部分) python 内置函数大讲堂 python全栈开发,内置函数 1. 内置函数 python的内置函数截止到python版本3.6.2,现在python一共为 ...
随机推荐
- C语言学习(三)
一.数组.循环.判断条件 #include<stdio.h> int main(){ int a =100; int b =200; int i; int arr [5]; if (a ...
- jvm源码解读--18 Java的start()方法解读 以及 wait 和notify流程图
drawwed by 张艳涛 and get info from openjdk8 还有一个图
- 记intouch SMC local下驱动丢失问题解决
最近项目中,维护发现Intouch 2014R2版本下,有一台上位机SMC下local安装的Dassdirect和dasmbtcp驱动都丢失了,无法查看.但不影响程序的正常使用,遂进行相应的寻求帮助, ...
- js之检测浏览器
getBrowser () { let ua = navigator.userAgent.toLocaleLowerCase() let browserType = null if (ua.match ...
- SAS 按自定义顺序对观测进行排序
本文链接:https://www.cnblogs.com/snoopy1866/p/15091967.html 实际项目中会经常遇到按指定顺序输出Listing的情况,例如:输出所有受试者的分组情况列 ...
- Magento 2.2 SQL注入漏洞
影响版本 2.2.* poc地址 https://github.com/ambionics/magento-exploits python3 magento-sqli.py http://192.1 ...
- ;~ 并发运行的AutoHotkey脚本真机实际测试模板参考20191010.ahk
;~ 并发运行的AutoHotkey脚本真机实际测试模板参考20191010.ahk;~ 2019年10月10日;~ 徐晓亮(aahk6188);~ 操作系统测试环境: Windows 7 专业版 3 ...
- ;~ 小部分AutoHotkey源代码片段测试模板2019年10月9日.ahk
;~ 小部分AutoHotkey源代码片段测试模板2019年10月9日.ahk ;~ 此脚本用于测试执行一行或多行AHK脚本源代码的效果;~ 此脚本最后修改于2019年9月22日20时03分;~ 把此 ...
- ICCV2021 | 重新思考视觉transformers的空间维度
论文:Rethinking Spatial Dimensions of Vision Transformers 代码:https://github.com/naver-ai/pit 获取:在CV技 ...
- noip模拟32[好数学啊]
noip模拟32 solutions 真是无语子,又没上100,无奈死了 虽然我每次都觉得题很难,但是还是有好多上100的 战神都200多了,好生气啊啊啊 从题开始变难之后,我的时间分配越来越不均匀, ...