详解Python 函数参数的拆解


Posted in Python onSeptember 02, 2020

本文为阅读 《Python Tricks: The Book》一书的 3.5 Function Argument Unpacking 的笔记与扩充理解。函数参数拆解是定义可变参数(VarArgs) *args**kwargs 的反向特性。

*args**kwars 是函数可定义一个形参来接收传入的不定数量的实参。

而这里的函数参数拆解是形参定义多个,在调用时只传入一个集合类型对象(带上 * 或 ** 前缀),如 list, tuple, dict, 甚至是 generator, 然后函数能自动从集合对象中取得对应的值。

如果能理解下面赋值时的参数拆解和 Python 3.5 的新增 * ** 操作,那么于本文讲述的特性就好理解了。

唯一的不同时作为参数的集合传入函数时必须前面加上 ***, 以此宣告该参数将被拆解,而非一个整体作为一个函数参数。加上 * ** 与 Java 的 @SafeVarargs 有类似的功效,最接近的是 Scala 的 foo(Array[String]("d", "e") : _*) 写法。参见:Java 和 Scala 调用变参的方式

Python 的赋值拆解操作

>>> a, b = [1, 2] # a, b = (1, 2) 也是一样的效果
>>> print(a, b)
1 2
>>> a, b = {'x': 1, 'y':2}
>>> print(a, b)
x y
>>> a, b = {'x': 1, 'y':2}.keys()
>>> print(a, b)
x y
>>> a, b = {'x': 1, 'y':2}.values()
>>> print(a, b)
1 2
>>> a, b = (x * x for x in range(2))
>>> print(a, b)
0 1

Python 3.5 的新增拆解操作

>>> [1, 2, *range(3), *[4, 5], *(6, 7)] # * 号能把集合打散,flatten(unwrap)
[1, 2, 0, 1, 2, 4, 5, 6, 7]
>>> {'x': 1, **{'y': 2, 'z': 3}}   # ** 把字典打散, flatten(unwrap) 操作
{'x': 1, 'y': 2, 'z': 3}

有些像是函数编程中的 flatten unwrap 操作。

有了上面的基础后,再回到原书中的例子,当我们定义如下打印 3-D 坐标的函数

def print_vector(x, y, z):
 print('<%s, %s, %s>' % (x, y, z))

依次传入三个参数的方式就不值不提了,现在就看如何利用函数的参数拆解特性,只传入一个集合参数,让该 print_vector 函数准确从集合中获得相应的 x, y, 和 z 的值。

函数参数拆解的调用举例

>>> list_vec = [2, 1, 3]
>>> print_vector(*list_vec)
<2, 1, 3>
>>> print_vector(*(2, 1, 3))
<2, 1, 3>
>>> dict_vec = {'y': 2, 'z': 1, 'x': 3}
>>> print_vector(*dict_vec) # 相当于 print_vector(*dict_vec.keys())
<y, z, x>
>>> print_vector(**dict_vec) # 相当于 print_vector(dict_vec['x'], dict_vec['y'], dict_vec['z']
<3, 2, 1>
>>> genexpr = (x * x for x in range(3))
>>> print_vector(*genexpr)
<0, 1, 4>
>>> print_vector(*dict_vec.values()) # 即 print_vector(*list(dict_vec.values()))
<2, 1, 3>

注意 **dict_vec 有点不一样,它的内容必须是函数 print_vector 的形参 'x', 'y', 'z' 作为 key 的三个元素。

以下是各种错误

**dict_vec 元素个数不对,或 key 不匹配时的错误

>>> print_vector(**{'y': 2, 'z': 1, 'x': 3})
<3, 2, 1>
>>> print_vector(**{'y': 2, 'z': 1, 'a': 3})  #元素个数是3 个,但出现 x, y, z 之外的 key
Traceback (most recent call last):
 File "<pyshell#39>", line 1, in <module>
 print_vector(**{'y': 2, 'z': 1, 'a': 3})
TypeError: print_vector() got an unexpected keyword argument 'a'
>>> print_vector(**{'y': 2, 'z': 1, 'x': 3, 'a': 4}) # 包含有 x, y, z, 但有四个元素,key 'a' 不能识别
Traceback (most recent call last):
 File "<pyshell#40>", line 1, in <module>
 print_vector(**{'y': 2, 'z': 1, 'x': 3, 'a': 4})
TypeError: print_vector() got an unexpected keyword argument 'a'
>>> print_vector(**{'y': 2, 'z': 1})   # 缺少 key 'x' 对应的元素
Traceback (most recent call last):
 File "<pyshell#41>", line 1, in <module>
 print_vector(**{'y': 2, 'z': 1})
TypeError: print_vector() missing 1 required positional argument: 'x'

不带星星的错误

>>> print_vector([2, 1, 3])
Traceback (most recent call last):
 File "<pyshell#44>", line 1, in <module>
 print_vector([2, 1, 3])
TypeError: print_vector() missing 2 required positional arguments: 'y' and 'z'

把集合对象整体作为第一个参数,所以未传入 y 和 z,因此必须用前缀 * 或 ** 通告函数进行参数拆解

集合长度与函数参数个数不匹配时的错误

>>> print_vector(*[2, 1])    # 拆成了 x=2, y=1, 然后 z 呢?
Traceback (most recent call last):
 File "<pyshell#47>", line 1, in <module>
 print_vector(*[2, 1])
TypeError: print_vector() missing 1 required positional argument: 'z'
>>> print_vector(*[2, 1, 3, 4])  # 虽然拆出了 x=2, y=1, z=3, 但也别想强塞第四个元素给该函数(只定义的三个参数)
Traceback (most recent call last):
 File "<pyshell#48>", line 1, in <module>
 print_vector(*[2, 1, 3, 4])
TypeError: print_vector() takes 3 positional arguments but 4 were given

上面这两个错误与赋值时的拆解因元素个数不匹配时的错误是相对应的

>>> a, b = [1]
Traceback (most recent call last):
 File "<pyshell#54>", line 1, in <module>
 a, b = [1]
ValueError: not enough values to unpack (expected 2, got 1)
>>> a, b = [1, 2, 3]
Traceback (most recent call last):
 File "<pyshell#55>", line 1, in <module>
 a, b = [1, 2, 3]
ValueError: too many values to unpack (expected 2)

当然在赋值时 Python 可以像下面那样做

a, b, *c = [1, 2, 3, 4]
>>> print(a, b, c)
1 2 [3, 4]

补充(2020-07-02): 迭代的拆解在 Python 中的术语是 Iterable Unpacking, 找到两个相关的 PEP 448, PEP 3132。在实际上用处还是很大的,比如在拆分字符串时只关系自己有兴趣的字段

line = '2020-06-19 22:14:00  2688 abc.json'
date, time, size, name = line.split() # 获得所有字段值
_, time, _, name = line.split()   # 只对 time 和 name 有兴趣
date, *_ = line.split()     # 只对第一个 date 有兴趣
*_, name = line.split()     # 只对最后的 name 有兴趣
date, *_, name = line.split()   # 对两边的 date, name 有兴趣

这样就避免了用索引号来引用拆分后的值,如 split[0], splint[2] 等,有名的变量不容易出错。注意到 Python 在拆解时非常聪明,它知道怎么去对应位置,用了星号(*) 的情况,明白如何处理前面跳过多少个,中间跳过多少个,或最后收集多少个元素。

链接:

PEP 448 -- Additional Unpacking Generalizations
PEP 3132 -- Extended Iterable Unpacking

以上就是详解Python 函数参数的拆解的详细内容,更多关于python 函数参数拆解的资料请关注三水点靠木其它相关文章!

Python 相关文章推荐
python实现的jpg格式图片修复代码
Apr 21 Python
用virtualenv建立多个Python独立虚拟开发环境
Jul 06 Python
Python实现生成随机数据插入mysql数据库的方法
Dec 25 Python
Python计算一个给定时间点前一个月和后一个月第一天的方法
May 29 Python
python之Flask实现简单登录功能的示例代码
Dec 24 Python
spark dataframe 将一列展开,把该列所有值都变成新列的方法
Jan 29 Python
PyQt5重写QComboBox的鼠标点击事件方法
Jun 25 Python
Django Rest framework解析器和渲染器详解
Jul 25 Python
python+selenium 鼠标事件操作方法
Aug 24 Python
Python获取指定网段正在使用的IP
Dec 14 Python
使用豆瓣源来安装python中的第三方库方法
Jan 26 Python
Pandas实现DataFrame的简单运算、统计与排序
Mar 31 Python
Python 常用日期处理 -- calendar 与 dateutil 模块的使用
Sep 02 #Python
python 常用日期处理-- datetime 模块的使用
Sep 02 #Python
详解Python中的路径问题
Sep 02 #Python
python dict如何定义
Sep 02 #Python
python基本算法之实现归并排序(Merge sort)
Sep 01 #Python
在pycharm中文件取消用 pytest模式打开的操作
Sep 01 #Python
Python内置函数property()如何使用
Sep 01 #Python
You might like
在PHP中使用Sockets 从Usenet中获取文件
2008/01/10 PHP
php下mysql数据库操作类(改自discuz)
2010/07/03 PHP
新浪微博API开发简介之用户授权(PHP基础篇)
2011/09/25 PHP
PHP+MySQL插入操作实例
2015/01/21 PHP
mysql_escape_string()函数用法分析
2016/04/25 PHP
PHP中用Trait封装单例模式的实现
2019/12/18 PHP
nginx 设置多个站跨域
2021/03/09 Servers
javascript获取下拉列表框当中的文本值示例代码
2013/07/31 Javascript
jQuery把表单元素变为json对象
2013/11/06 Javascript
js判断当前浏览器类型,判断IE浏览器方法
2014/06/02 Javascript
jquery插件jquery.nicescroll实现图片无滚动条左右拖拽的方法
2015/08/10 Javascript
Javascript iframe交互并兼容各种浏览器的解决方法
2016/07/12 Javascript
ES6记录异步函数的执行时间详解
2016/08/31 Javascript
微信小程序加载更多 点击查看更多
2016/11/29 Javascript
jquery,js简单实现类似Angular.js双向绑定
2017/01/13 Javascript
JS中利用localStorage防止页面动态添加数据刷新后数据丢失
2017/03/10 Javascript
vue loadmore组件上拉加载更多功能示例代码
2017/07/19 Javascript
Vue中正确使用jQuery的方法
2017/10/30 jQuery
关于vuejs中v-if和v-show的区别及v-show不起作用问题
2018/03/26 Javascript
vue cli2.0单页面title修改方法
2018/06/07 Javascript
vue-router中的hash和history两种模式的区别
2018/07/17 Javascript
基于Vue-cli快速搭建项目的完整步骤
2018/11/03 Javascript
微信浏览器下拉黑边解决方案 wScroollFix
2020/01/21 Javascript
微信小程序canvas开发水果老虎机的思路详解
2020/02/07 Javascript
使用python 获取进程pid号的方法
2014/03/10 Python
python数据结构之图的实现方法
2015/07/08 Python
python中使用xlrd读excel使用xlwt写excel的实例代码
2018/01/31 Python
python 随机生成10位数密码的实现代码
2019/06/27 Python
python 绘制场景热力图的示例
2020/09/23 Python
波兰珠宝品牌:YES
2019/08/09 全球购物
退休感言
2014/01/28 职场文书
最新会计专业求职信范文
2014/01/28 职场文书
外贸专业求职信
2014/03/09 职场文书
解除合同协议书
2014/04/17 职场文书
协议书模板
2014/04/23 职场文书
2014年内部审计工作总结
2014/12/09 职场文书