跟老齊學Python之再深點,更懂list_python

來源:互聯網
上載者:User

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 0sunday is 1friday is 2

python中提供了一個內建函數enumerate,能夠實作類別似的功能

>>> for (i,day) in enumerate(week):...   print day+' is '+str(i)... monday is 0sunday is 1friday 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')這樣的東西,這是另外一種資料類型,待後面詳解。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.