Python函数中,参数前*的作用

在查看zip()资料时,发现在函数的参数前,有*,没有理解具体含义,于是在搜索引擎bing里搜索python *,没有结果。

后来搜索python zip(*)时,总算有点眉目,在stackoverflow中有相关问题的解答。


当时看的博客python zip()用法的博客链接是:

http://www.cnblogs.com/frydsh/archive/2012/07/10/2585370.html

里面涉及到*在参数前使用的例子,其实作者也在下面解释了,但是我是小白,没太理解,于是在stackoverflow中看到有大神链接了Python tutorial的具体解释,链接如下:

https://docs.python.org/3/tutorial/controlflow.html#tut-unpacking-arguments

里面有例子,说的很清楚,下面是粘贴Python手册中关于*的使用介绍。

4.7.4. Unpacking Argument Lists

The reverse situation occurs when the arguments are already in a list or tuplebut need to be unpacked for a function call requiring separate positionalarguments. For instance, the built-inrange() function expects separatestart andstop arguments. If they are not available separately, write thefunction call with the*-operator to unpack the arguments out of a listor tuple:

>>>
>>> list(range(3, 6))            # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> list(range(*args))            # call with arguments unpacked from a list
[3, 4, 5]

In the same fashion, dictionaries can deliver keyword arguments with the**-operator:

>>>
>>> def parrot(voltage, state='a stiff', action='voom'):
...     print("-- This parrot wouldn't", action, end=' ')
...     print("if you put", voltage, "volts through it.", end=' ')
...     print("E's", state, "!")
...
>>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
>>> parrot(**d)
-- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !

看了这两个例子,是不是对于python函数中,参数前*的使用立刻清晰起来了!!!

stackoverflow问题的地址在这里:https://stackoverflow.com/questions/2511300/why-does-x-y-zipzipa-b-work-in-python

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值