欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 能源 > python 之单星号(*)与双星号(**)

python 之单星号(*)与双星号(**)

2025/9/14 17:31:20 来源:https://blog.csdn.net/zhaoluruoyan89/article/details/142822656  浏览:    关键词:python 之单星号(*)与双星号(**)

一、作为运算符

*表示乘法运算
**表示乘方运算

print(f"a = {3 * 2}")  # 输出6
print("b = {}".format(3 ** 2))  # 输出9

二、作为函数形参

*在python中做函数形参,表示的是一个可变长度的序列,类型为tuple,即将所有参数放入一个元组(tuple)中,被函数使用。
**在python中做函数形参,表示的是一个可变长度的序列,类型为dict,即将所有的关键字参数,放入一个字典(dict)中, 被函数使用。
*与**作为形参同时出现时,**必须在最后面

def printx(*arg1, **arg2):print("arg1={0}, type:{1}".format(arg1, type(arg1)))print("arg2={0}, type:{1}".format(arg2, type(arg2)))P1 = printx(1, 2, key1=1, key2=2) ## 此时1, 2 即为*arg1; key1=1, key2=2 即为**arg2
#output
#arg1=(1, 2), type:<class 'tuple'>
#arg2={'key1': 1, 'key2': 2}, type:<class 'dict'>

三、作为函数实参

在list/tuple/set前加*,会把序列中的所有元素解包成位置参数
在dict前加*,会把dict的键变成位置参数;加**,把字典的键值对变成关键字参数。
A = (a,b,c)
B = {“key1” :1, “key2”:2}
P3 = Printx(*A) # 等同于printx(a,b,c)
P3 = Printx(*A, *B) #等同于printx(a,b,c,key1,key2)
P3 = Printx(*A, **B) #等同于printx(a,b,c,key1=1,key2=2)

def printx(*arg1, **arg2):print("arg1={0}, type:{1}".format(arg1, type(arg1)))print("arg2={0}, type:{1}".format(arg2, type(arg2)))#arg1={0}中的0对应的是format 里面的变量arg1 ,如果将0换成1 即arg1={1},此时arg1={1}中的1对应的是format 里面的变量type(arg1);A = (1, 2, 3)
K1 = {'key1': 1, 'key2': 2}
P2 = printx(*A, *K1)  # 注意在dict前加一个*,只把dict的 '键' 作为位置参传递
print('')
P3 = printx(*A, **K1) # 此时 #output
#arg1=(1, 2, 3, 'key1', 'key2'), type:<class 'tuple'>
#arg2={}, type:<class 'dict'>#arg1=(1, 2, 3), type:<class 'tuple'>
#arg2={'key1': 1, 'key2': 2}, type:<class 'dict'>

四、作为序列解包

注意序列解包时*解包为list,不再是tuple了

  1. 先对不带的变量解包,剩余的数据在划分给带的变量
    x,y,*z = 1,2,3,4,5 #等同于 x=1, y = 2, z= [3,4,5]
    x,*y,z = 1,2,3,4,5 #等同于 x=1, y = [2,3,4], z= 5
  2. 如果左值比右值要多,那么带 * 的变量默认为空列表
    x,y,*z = 1,2 #等同于 x=1, y = 2, z= []
    x,*y,z = 1,2 #x=1, y = [], z= 2
  3. 单*只解包dict的键, **解包dict键值对
    key_A = {‘key1’:1, ‘key2’:2}
    key_B = {“key3” :3, “key4”:4}
    X = {*key_A} #等同于x= {‘key1’, ’key2’}
    X = {**key_A} #等同于x= {‘key1’:1, ‘key2’:2}
    X = {**key_A, **key_B} #等同于组包,x={‘key1’:1, ‘key2’:2, “key3” :3, “key4”:4}


注意:

在Python中默认的函数参数顺序是:必选参数、默认参数、*args和**kwargs。如下所示:

def  testFunc(name, age=10, *agrs, **kwargs):pass


 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词