收集參數
- 未被定義的可以放入函數中的不限個數的參數
- 這些實參被收集為一個元胞數組(tuple)
- 語法:
1 def func(*argus): 2 func_body 3 4 # 調用 5 func(p1,p2,p3...)
關鍵字收集參數
- 把關鍵字參數按字典格式存入收集參數
- 語法:
1 def func(**kwargs): 2 func_body 3 4 # 調用 5 func(p1=v1,p2=v2,p3=v3...)
- details:
- 若原函數中有關鍵字形參 則形參對應實參外的多余參數被放入關鍵字收集參數中
栗子:
1 def func(**kwargs): 2 print('這是一個有關鍵字收集參數的函數') 3 print(type(kwargs)) 4 # 訪問字典中的內容格式!!!!!!!!! 5 for k,v in kwargs.items(): 6 print(k,'=',v) 7 8 9 10 func(a='A',b=2,c=3)
執行結果:
這是一個有關鍵字收集參數的函數
<class 'dict'> a = A b = 2 c = 3
參數混合使用時的調用順序
這個不好說 📕 啦啦啦 小栗子幫忙解釋下(*Φ皿Φ*)
栗子:
1 # 開學時的自我介紹 2 # 注意參數的順序們 3 def stu(name,age,*args,hobby='none',**kwargs): 4 print('hello everyone') 5 print('i am {0}, {1} years old'.format(name,age)) 6 if hobby == 'none': 7 print('sorry,i am a boring teenager') 8 else: 9 print('my hobby is {0}'.format(hobby)) 10 print('以下是收集參數') 11 # 又是收集參數的用法!!! 12 for i in args: 13 print(i) 14 print('以下是關鍵字收集參數') 15 for k,v in kwargs.items(): 16 print(k,'is',v) 17 18 19 stu(name='lily',age=18) 20 print() 21 stu('lily',18,'i am glad to meet all of you','lalalalala','happy very much!!!',hobby='pianting',hobby2='singing',hobby3='eating')
執行結果:
hello everyone i am lily, 18 years old sorry,i am a boring teenager 以下是收集參數 以下是關鍵字收集參數 hello everyone i am lily, 18 years old my hobby is pianting 以下是收集參數 i am glad to meet all of you lalalalala happy very much!!! 以下是關鍵字收集參數 hobby2 is singing hobby3 is eating
收集參數的解包
(將參數裝入list后 把list的值放入收集參數 而非把list放入收集參數)
栗子:
1 def func(*args): 2 for i in args: 3 print(type(i)) 4 print(i) 5 # 直接調用 6 l = [1,2,3,4,5] 7 func(l) 8 9 print() 10 # 對list進行解包(也用✳) 11 l1 = [5,4,3,2,1] 12 func(*l1)
執行結果:
<class 'list'> [1, 2, 3, 4, 5] <class 'int'> 5 <class 'int'> 4 <class 'int'> 3 <class 'int'> 2 <class 'int'> 1
補充:對字典格式的的訪問
🌰:
1 # 雙層列表(嵌套列表) 2 a = [[1,2,3],['q','w','e'],['*','*','*']] 3 # 遍歷 4 for x,y,z in a: 5 print(x,'-',y,'-',z) 6 # 看 它們是一一對應的
執行結果:
1 - 2 - 3 q - w - e * - * - *