python定义函数星号,令人困惑的python星号符号的双重用法(作为函数参数或函数定义)...

I'm a bit confused. Let's create a function called x. I know that by putting * before the y, this means that we can add as many arguments as we want.

def x(*y):

return y

However.

Case 1:

>>> x(1, 2)

(1, 2)

Case 2:

Let's pass a list [1,2] with an asterisk before it:

>>> x(*[1,2])

(1, 2)

It seems that the single asterisk has two uses:

For allowing multiple arguments in a function - essentially putting them into a list

If done twice, to "break apart" a list into separate items

Why is this? Why can't I do something like: *a*b?

解决方案

In function definition * is used to collect all positional arguments in a tuple, in a function call * unpacks an iterable and passes it's items as positional arguments.

If by *a*b you're trying to unpack two iterables/iterators a and b then correct way is:

>>> a = [1, 2, 4]

>>> b = 'foo'

>>> from itertools import chain

def func(*x):

print x

...

>>> func(*chain(a,b)) #chain will work for both iterators and iterables

(1, 2, 4, 'f', 'o', 'o')

if both a and b are of same type and are iterable then you can also use :

>>> a = [1, 2, 4]

>>> b = [0,1]

>>> func(*(a + b))

(1, 2, 4, 0, 1)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值