Python序列拆分操作符與映射拆分操作符執行個體

來源:互聯網
上載者:User

標籤:class   color   err   http   jpg   code   res   info   多個   

 

使用序列拆分操作符(*)來提供位置參數。

例如函數heron的參數存放於一個列表sides中,可以:heron(sides[0],sides[1],sides[2]) 也可以進行拆分:heron(*sides)。如果列表包含比函數參數更多的項數,就可以使用分區提取出合適的參數。

1.在使用可變數量的位置參數的函數時,可使用

序列拆分操作符(*)。

#1.此時,args是一個完整的序列,*args表示將一個序列中的所有元素拆分出來作為函數的參數
>>> def product(*args): result = 1 for arg in args: result *= arg return result#2.因此,傳參時應該傳同屬於一個序列的拆分後的元素>>> product(1,2,3,4)24 >>> product(5,3)15

可以將關鍵字參數放在位置參數後面,即def sum_of_power(*args,poewer=1):...

* 本身作為參數:表明在*後面不應該再出現位置參數,但關鍵字參數是允許的:def heron(a,b,c,*,unit="meters"):.....

如果將* 作為第一個參數,那麼不允許使用任何位置參數,並強制調用該函數時使用關鍵字參數:def print_set(*,paper="Letter",copies=1,color=False):...。可以不使用任何參數調用 print_set(),也可以改變某些或全部預設值。但如果使用位置參數,就會產生TypeError異常,比如print_set(“A4”)就會產 生異常。

 

 2.對映射進行拆分時,可使用

映射拆分操作符(**)

例如使用**將字典傳遞給print_set()函數:

 options = dict(paper="A4",color=True)

pritn_set(**options)

將字典的索引值對進行拆分,每個鍵的值被賦予適當的參數,參數名稱與鍵相同。

 在參數中使用**,建立的函數可以接受給定的任意數量的關鍵字參數:

>>> def add_person_details(ssn,surname,**kwargs):      print ("SSN=",ssn)    print ("surname=",surname)    for key in sorted(kwargs):    print ("{0}={1}".format(key,kwargs[key]))>>> add_person_details(123,"Luce",forename="Lexis",age=47)  SSN= 123 surname= Luce age=47 forename=Lexis >>> add_person_details(123,"Luce")SSN= 123surname= Luce

序列拆分符與映射拆分符舉例:

#此處,args是一個序列,*表示將args拆分,所以*args作為函數的第一參數時,表示print_args第一個參數的位置可以
#接受任意多個元素(同屬於一個序列的),對於**kwargs參數也是同樣的道理
>>> def print_args(*args, **kwargs): for i,arg in enumerate(args): print "positional argument{0}={1}".format(i,arg) for key in kwargs: print "keyword argument{0}={1}".format(key,kwargs[key]) >>> print_args(‘a‘,‘b‘,‘c‘,‘d‘,name=‘Tom‘,age=12,sex=‘f‘)

結果:

映射拆分舉例:

name="jack"age=24s="name is {name} and age is {age}".format(**locals())print s

結果:

 

參考文獻:Mark Summerfield.《Python3程式開發指南》.149-151.

Python序列拆分操作符與映射拆分操作符執行個體

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.