list解析
先看下面的例子,這個例子是想得到1到9的每個整數的平方,并且將結果放在list中打印出來
>>> power2 = [] >>> for i in range(1,10): ... power2.append(i*i) ... >>> power2 [1, 4, 9, 16, 25, 36, 49, 64, 81]
python有一個非常有意思的功能,就是list解析,就是這樣的:
>>> squares = [x**2 for x in range(1,10)] >>> squares [1, 4, 9, 16, 25, 36, 49, 64, 81]
看到這個結果,看官還不驚嘆嗎?這就是python,追求簡潔優雅的python!
其官方文檔中有這樣一段描述,道出了list解析的真諦:
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.
還記得前面一講中的那個問題嗎?
找出100以內的能夠被3整除的正整數。
我們用的方法是:
aliquot = [] for n in range(1,100): if n%3 == 0: aliquot.append(n) print aliquot
好了。現在用list解析重寫,會是這樣的:
>>> 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]
震撼了。絕對牛X!
其實,不僅僅對數字組成的list,所有的都可以如此操作。請在平復了激動的心之后,默默地看下面的代碼,感悟一下list解析的魅力。
>>> mybag = [' glass',' apple','green leaf '] #有的前面有空格,有的后面有空格 >>> [one.strip() for one in mybag] #去掉元素前后的空格 ['glass', 'apple', 'green leaf'] enumerate
這是一個有意思的內置函數,本來我們可以通過for i in range(len(list))的方式得到一個list的每個元素編號,然后在用list[i]的方式得到該元素。如果要同時得到元素編號和元素怎么辦?就是這樣了:
>>> for i in range(len(week)): ... print week[i]+' is '+str(i) #注意,i是int類型,如果和前面的用+連接,必須是str類型 ... monday is 0 sunday is 1 friday is 2
python中提供了一個內置函數enumerate,能夠實現類似的功能
>>> for (i,day) in enumerate(week): ... print day+' is '+str(i) ... monday is 0 sunday is 1 friday is 2
算是一個有意思的內置函數了,主要是提供一個簡單快捷的方法。
官方文檔是這么說的:
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:
順便抄錄幾個例子,供看官欣賞,最好實驗一下。
>>> 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')這樣的東西,這是另外一種數據類型,待后面詳解。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
