list解析
先看下面的例子,這個(gè)例子是想得到1到9的每個(gè)整數(shù)的平方,并且將結(jié)果放在list中打印出來(lái)
?123456 >>> power2 = [] >>> for i in range(1,10): ... power2.append(i*i) ... >>> power2 [1, 4, 9, 16, 25, 36, 49, 64, 81]
python有一個(gè)非常有意思的功能,就是list解析,就是這樣的:
?123 >>> squares = [x**2 for x in range(1,10)] >>> squares [1, 4, 9, 16, 25, 36, 49, 64, 81]
看到這個(gè)結(jié)果,看官還不驚嘆嗎?這就是python,追求簡(jiǎn)潔優(yōu)雅的python!
其官方文檔中有這樣一段描述,道出了list解析的真諦:
?1 List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.
還記得前面一講中的那個(gè)問(wèn)題嗎?
找出100以內(nèi)的能夠被3整除的正整數(shù)。
我們用的方法是:
?1234567 aliquot = [] for n in range(1,100): if n%3 == 0: aliquot.append(n) print aliquot
好了。現(xiàn)在用list解析重寫(xiě),會(huì)是這樣的:
?123 >>> aliquot = [n for n in range(1,100) if n%3==0] >>> aliquot [3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99]
震撼了。絕對(duì)牛X!
其實(shí),不僅僅對(duì)數(shù)字組成的list,所有的都可以如此操作。請(qǐng)?jiān)谄綇?fù)了激動(dòng)的心之后,默默地看下面的代碼,感悟一下list解析的魅力。
?1234 >>> mybag = [' glass',' apple','green leaf '] #有的前面有空格,有的后面有空格 >>> [one.strip() for one in mybag] #去掉元素前后的空格 ['glass', 'apple', 'green leaf'] enumerate
這是一個(gè)有意思的內(nèi)置函數(shù),本來(lái)我們可以通過(guò)for i in range(len(list))的方式得到一個(gè)list的每個(gè)元素編號(hào),然后在用list[i]的方式得到該元素。如果要同時(shí)得到元素編號(hào)和元素怎么辦?就是這樣了:
?123456 >>> for i in range(len(week)): ... print week[i]+' is '+str(i) #注意,i是int類型,如果和前面的用+連接,必須是str類型 ... monday is 0sunday is 1friday is 2
python中提供了一個(gè)內(nèi)置函數(shù)enumerate,能夠?qū)崿F(xiàn)類似的功能
?123456 >>> for (i,day) in enumerate(week): ... print day+' is '+str(i) ... monday is 0sunday is 1friday is 2
算是一個(gè)有意思的內(nèi)置函數(shù)了,主要是提供一個(gè)簡(jiǎn)單快捷的方法。
官方文檔是這么說(shuō)的:
復(fù)制代碼 代碼如下:
Return an enumerate object. sequence must be a sequence, an iterator, or some other object which supports iteration. The next() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over sequence:
順便抄錄幾個(gè)例子,供看官欣賞,最好實(shí)驗(yàn)一下。
?12345 >>> seasons = ['Spring', 'Summer', 'Fall', 'Winter'] >>> list(enumerate(seasons)) [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')] >>> list(enumerate(seasons, start=1)) [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
在這里有類似(0,'Spring')這樣的東西,這是另外一種數(shù)據(jù)類型,待后面詳解。
更多信息請(qǐng)查看IT技術(shù)專欄