2021年1月17日 / 874次阅读 / Last Modified 2021年2月5日
当python函数返回tuple或list时,有一个隐藏的unpack机制,终于被我发现了!
正常获取返回的tuple或list是这样的:
>>> def ta():
... return 1,2,3
...
>>> def tb():
... return [1,2,3]
...
>>> a = ta()
>>> a
(1, 2, 3)
>>> b = tb()
>>> b
[1, 2, 3]
我们其实还可以这样:
>>> a,b,c = ta()
>>> a
1
>>> b
2
>>> c
3
>>> a,b,c = tb()
>>> a
1
>>> b
2
>>> c
3
这就是直接在函数返回的时候,unpack返回的tuple或list。
因此,以后再看到下面这样的代码,不要惊讶,不要疑惑:
>>> a, = test()
>>> a
1
>>> b, = tesu()
>>> b
1
为什么a和b后面有个逗号?因为test和tesu这两个函数是这样的:
>>> def test():
... return 1,
...
>>> def tesu():
... return [1]
test和tesu函数返回的是tuple和list,而且只有1个元素在里面,a和b后面带个逗号,表示直接取tuple或list里的第1个元素。这样a和b就是元素,而不是tuple或list对象。
有的函数在设计的时候,返回是tuple或list,但是tuple或list的长度(里面的元素个数)是由输入来确定的,因此确定输入,就能够确定输出对象的元素个数,就可以知道编写代码的时候,需要多个变量来承接每一个返回的元素:
>>> def ft(*a):
... return a
...
>>> a, = ft(1)
>>> a
1
>>> a,b = ft(1,2)
>>> a
1
>>> b
2
>>> a,b,c = ft(4,5,6)
>>> a
4
>>> b
5
>>> c
6
>>> a,b,c, = ft('a','b','c')
>>> a
'a'
>>> b
'b'
>>> c
'c'
写成 a,b,c, = ft('a','b','c') 也OK,c后面也可由跟个逗号,语法上是OK的,只要返回的元素个数,与承接的变量数量能够匹配上。
-- EOF --
本文链接:https://www.pynote.net/archives/3234
《当python函数返回tuple或list时...》有2条留言
前一篇:神经元激活函数
后一篇:MLP网络BP公式推导
©Copyright 麦新杰 Since 2019 Python笔记
在Python官方教程上看到: The statement t = 12345, 54321, 'hello!' is an example of tuple packing: the values 12345, 54321 and 'hello!' are packed together in a tuple. The reverse operation is also possible: x, y, z = t [ ]
在赋值的时候,还可以这样:
size是tuple,width和height是普通int,一口气全赋值了。 [ ]