import numpy as np
# *在 = 的右边,表示解包操作,将可迭代对象中的每个元素分散开并赋值给等号左边的变量
#python 函数传参打包
a = { "name":"wzc","age":13,"school":"bupt"}
print(a)
def func1(age,name,school):
print('name: ', name)
print('age: ', age)
print('school: ', school)
# ** 解包字典会将字典中key的表达式与函数参数列表进行匹配,将key的值赋值给名称与key相同的函数形参,如果形参列表中没有与传入参数key相匹配的形参,则报错
print("-"*20 , "**在函数传参时解包字典" , '-'*20)
func1(**a)
# * 解包字典只是按照从左到右的顺序将字典的key赋值给形参
print("-"*20 , "*在函数传参时解包字典" , '-'*20)
func1(*a)
def func2(age,name,school):
print('name: ', name)
print('age: ', age)
print('school: ', school)
# * 号解包列表,元组,如果是普通的表达式,则=右边不需要写*,解包时按照顺序赋值
print("-"*20 , "普通表达式解包列表" , '-'*20)
c,d,e = [13,"wzc","bupt"]
print(c);print(d);print(e)
# ** 号解包列表,元组,如果是普通的表达式,则=右边不需要写**,解包时默认按照顺序赋值字典的key,如果想解包value,可以调用.values()
print("-"*20 , "普通表达式解包字典" , '-'*20)
c,d,e = a
print(c);print(d);print(e)
print("-"*20 , "*在函数传参时解包列表" , '-'*20)
func2(*[13,"wzc","bupt"])
print("-"*20 , "*在函数传参时解包元组" , '-'*20)
func2(*(13,'wzc','bupt'))
# *,**放在等号左边为打包
#在函数传参的时候*将传入的多个值打包为一个元组
#**将多个 变量 = 值 打包为一个字典,其中的每个元素为 变量名:值
def func3(*args, **kargs):
print("args: ",args)
print("kargs: ", kargs)
func3("a","b",1,2,3,name = "wzc",age = "13",school = "bupt")
#在一般的赋值语句中,将右边多个值打包为一个列表
*c,d = "a","b",1,2,3
print(c);print(d)
python * ** 打包和解包
最新推荐文章于 2024-08-14 23:30:40 发布