【转载】python 函数的入参 一个* 两个* 的使用与区别

1. 转自: https://www.cnblogs.com/liumengchen-boke/p/5848400.html

* 函数接收参数为元组

 例如 

def myfun(*args): #相当于 def myfun(1,2,3)    ==> args 就相当于(1,2,3)

  for a in args:

    print(a)

** 表示函数接收参数为一个字典

def myfun(**args) :#相当于 def myfun({a:1,b:2,c:3}) ==>args 就相当于{a:1,b:2,c:3}

  for k,v in args:

    print(k,":",v)

2. 转自: https://www.cnblogs.com/ShawnYuki/p/6932658.html

3. 一个* 可变参数与元组 list的关系: 

转自:https://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001374738449338c8a122a7f2e047899fc162f4a7205ea3000

可变参数

在Python函数中,还可以定义可变参数。顾名思义,可变参数就是传入的参数个数是可变的,可以是1个、2个到任意个,还可以是0个。

我们以数学题为例子,给定一组数字a,b,c……,请计算a2 + b2 + c2 + ……。

要定义出这个函数,我们必须确定输入的参数。由于参数个数不确定,我们首先想到可以把a,b,c……作为一个list或tuple传进来,这样,函数可以定义如下:

def calc(numbers):
    sum = 0
    for n in numbers:
        sum = sum + n * n
    return sum

但是调用的时候,需要先组装出一个list或tuple:

>>> calc([1, 2, 3])
14
>>> calc((1, 3, 5, 7))
84

如果利用可变参数,调用函数的方式可以简化成这样:

>>> calc(1, 2, 3)
14
>>> calc(1, 3, 5, 7)
84

所以,我们把函数的参数改为可变参数:

def calc(*numbers):
    sum = 0
    for n in numbers:
        sum = sum + n * n
    return sum

定义可变参数和定义list或tuple参数相比,仅仅在参数前面加了一个*号。在函数内部,参数numbers接收到的是一个tuple,因此,函数代码完全不变。但是,调用该函数时,可以传入任意个参数,包括0个参数:

>>> calc(1, 2)
5
>>> calc()
0

如果已经有一个list或者tuple,要调用一个可变参数怎么办?可以这样做:

>>> nums = [1, 2, 3]
>>> calc(nums[0], nums[1], nums[2])
14

这种写法当然是可行的,问题是太繁琐,所以Python允许你在list或tuple前面加一个*号,把list或tuple的元素变成可变参数传进去:

>>> nums = [1, 2, 3]
>>> calc(*nums)
14

这种写法相当有用,而且很常见。

综上,

定义的时候使用*, 是将入参入参转换成lst, tuple.

调用的时候用*, 是将list 或者 tuple转换 成可变参数作为入参。

以下为自己的例子: 

def get_three_str():
    return "hello", "the", "word"

list_three_str = get_three_str()

print(list_three_str[0])
#次数输出的是列表, 结果为three str: ('hello', 'the', 'word')
print("three str: {}".format(list_three_str))
#此次输出的是可变参数, 结果为three str: hello, the, word
print("three str: {}, {}, {}".format(*list_three_str))

def get_the_fisrt_str(lst):
    print(lst[1])

def print_str(first, second, third):
    print("fisrt : {}".format(first))
    print(f"second : {second}")
    str = "third : " + third
    print(str)

get_the_fisrt_str(list_three_str)
print_str(*list_three_str)
 

猜你喜欢

转载自blog.csdn.net/u013985241/article/details/83742511
今日推荐