python基礎之不定長引數
阿新 • • 發佈:2018-12-05
例1:
def test(a,b,c=10,*args): # 預設引數c,要放在a,b的後面
print("a=%s" %a)
print("b=%s" %b)
print("c=%s" %c)
print("args:")
for each in args:
print(each)
>>> test(1,2,3,44,55,66,77,88) # 1傳給a,2傳給b,3傳給c,44,55,66,77,88傳給args
a=1
b=2
c=3
args:
44
55
66
77
88
>>> def test(a,b,c=10,*args,**kwargs): print("a=%s" %a) print("b=%s" %b) print("c=%s" %c) print("args:") for each in args: print(each) print("kwargs-items:") # 可以將kwargs理解為字典 for each in kwargs.items(): #列印items print(each) print("kwargs-keys:") for each in kwargs.keys(): #列印Keys print(each) print("kwargs-values:") for each in kwargs.values(): #列印values print(each) >>> test(1,2,3,44,55,name="wang qing",age=23,gender="girl",job="HR") a=1 b=2 c=3 args: 44 55 kwargs-items: ('name', 'wang qing') ('age', 23) ('gender', 'girl') ('job', 'HR') kwargs-keys: name age gender job kwargs-values: wang qing 23 girl HR
例 2:
>>> A=[22,33,44] >>> B={"name":"wang han","age":33,"gender":"boy","job":"Manager"} >>> def test(a,*args,**kwargs): print("a=%s" %a) print("args:") for each in args: print(each) print("kwargs:") for each in kwargs: print(each) >>> test(1,A,B) # A作為整體傳入args,B並非以鍵值對的形式傳入,作為整體傳入args,沒有引數傳入kwargs a=1 args: [22, 33, 44] {'name': 'wang han', 'age': 33, 'gender': 'boy', 'job': 'Manager'} kwargs:
可將以上程式碼中A,B進行拆包後傳入:
>>> A=[22,33,44] >>> B={"name":"wang han","age":33,"gender":"boy","job":"Manager"} >>> def test(a,*args,**kwargs): print("a=%s" %a) print("args:") for each in args: print(each) print("kwargs:") for each in kwargs: print(each) >>> test(1,*A,**B) # 傳參時,先將A,B拆包,一個*拆列表,兩個**拆字典 a=1 args: 22 33 44 kwargs: name age gender job