本文實(shí)例講述了Python cookbook(數(shù)據(jù)結(jié)構(gòu)與算法)將序列分解為單獨(dú)變量的方法。分享給大家供大家參考,具體如下:
如果對(duì)象是可迭代的(任何序列),則可以進(jìn)行分解操作,包括元組、列表、字符串、文件、迭代器以及生成器,可通過簡(jiǎn)單的一個(gè)賦值操作分解為單獨(dú)的變量。
唯一要求:變量的總數(shù)和序列相吻合,否則將出錯(cuò);
Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32Type "copyright", "credits" or "license()" for more information.>>> p=[4,5]>>> p[4, 5]>>> x,y=p>>> x4>>> y5>>> data=['lucy',50,12.1,(2016,07,31)]>>> data['lucy', 50, 12.1, (2016, 7, 31)]>>> name,shares,price,date=data>>> name'lucy'>>> shares50>>> price12.1>>> date(2016, 7, 31)>>> name,shares,price,(year,mon,day)=data>>> name'lucy'>>> shares50>>> price12.1>>> year2016>>> mon7>>> day31>>> s='hello'>>> s'hello'>>> a,b,c,d,e=s>>> c'l'>>> d'l'>>> e'o'>>> data=['lucy',50,12.1,(2016,07,31)]>>> _,shares,price,_=data #當(dāng)想丟棄某些值時(shí),可以選一個(gè)用不到的變量名作為要丟棄的值的名稱,比如此處“_”>>> shares50>>> price12.1>>>
注意:請(qǐng)確保丟棄的值選擇的變量名在其他地方未曾用到過。
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選