Python中l(wèi)ist列表的一些進(jìn)階使用方法介紹
判斷一個(gè) list 是否為空
傳統(tǒng)的方式:
if len(mylist): # Do something with my list else: # The list is empty
由于一個(gè)空 list 本身等同于 False,所以可以直接:
if mylist: # Do something with my list else: # The list is empty
遍歷 list 的同時(shí)獲取索引
傳統(tǒng)的方式:
i = 0 for element in mylist: # Do something with i and element i += 1
這樣更簡潔些:
for i, element in enumerate(mylist): # Do something with i and element pass
list 排序
在包含某元素的列表中依據(jù)某個(gè)屬性排序是一個(gè)很常見的操作。例如這里我們先創(chuàng)建一個(gè)包含 person 的 list:
class Person(object):
def __init__(self, age):
self.age = age
persons = [Person(age) for age in (14, 78, 42)]
傳統(tǒng)的方式是:
def get_sort_key(element): return element.age for element in sorted(persons, key=get_sort_key): print "Age:", element.age
更加簡潔、可讀性更好的方法是使用 Python 標(biāo)準(zhǔn)庫中的 operator 模塊:
from operator import attrgetter
for element in sorted(persons, key=attrgetter('age')):
print "Age:", element.age
attrgetter 方法優(yōu)先返回讀取的屬性值作為參數(shù)傳遞給 sorted 方法。operator 模塊還包括 itemgetter 和 methodcaller 方法,作用如其字面含義。
list解析
python有一個(gè)非常有意思的功能,就是list解析,就是這樣的:
>>> squares = [x**2 for x in range(1,10)] >>> squares [1, 4, 9, 16, 25, 36, 49, 64, 81]
看到這個(gè)結(jié)果,看官還不驚嘆嗎?這就是python,追求簡潔優(yōu)雅的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.
還記得前面一講中的那個(gè)問題嗎?
找出100以內(nèi)的能夠被3整除的正整數(shù)。
我們用的方法是:
aliquot = []
for n in range(1,100):
if n%3 == 0:
aliquot.append(n)
print aliquot
好了?,F(xiàn)在用list解析重寫,會(huì)是這樣的:
>>> 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解析的魅力。
>>> mybag = [' glass',' apple','green leaf '] #有的前面有空格,有的后面有空格 >>> [one.strip() for one in mybag] #去掉元素前后的空格 ['glass', 'apple', 'green leaf']
enumerate
這是一個(gè)有意思的內(nèi)置函數(shù),本來我們可以通過for i in range(len(list))的方式得到一個(gè)list的每個(gè)元素編號(hào),然后在用list[i]的方式得到該元素。如果要同時(shí)得到元素編號(hào)和元素怎么辦?就是這樣了:
>>> 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中提供了一個(gè)內(nèi)置函數(shù)enumerate,能夠?qū)崿F(xiàn)類似的功能
>>> for (i,day) in enumerate(week): ... print day+' is '+str(i) ... monday is 0 sunday is 1 friday is 2
算是一個(gè)有意思的內(nèi)置函數(shù)了,主要是提供一個(gè)簡單快捷的方法。
官方文檔是這么說的:
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)一下。
>>> 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')]
相關(guān)文章
python利用高階函數(shù)實(shí)現(xiàn)剪枝函數(shù)
這篇文章主要為大家詳細(xì)介紹了python利用高階函數(shù)實(shí)現(xiàn)剪枝函數(shù)的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-03-03
關(guān)于python中密碼加鹽的學(xué)習(xí)體會(huì)小結(jié)
這篇文章主要介紹了關(guān)于python中密碼加鹽的學(xué)習(xí)體會(huì)小結(jié),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07
Python實(shí)現(xiàn)PIL圖像處理庫繪制國際象棋棋盤
本文主要介紹了Python實(shí)現(xiàn)PIL圖像處理庫繪制國際象棋棋盤,文中通過示例代碼介紹的非常詳細(xì),需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-07-07
python和pyqt實(shí)現(xiàn)360的CLable控件
這篇文章主要介紹了python和pyqt實(shí)現(xiàn)360的CLable控件示例,需要的朋友可以參考下2014-02-02
二種python發(fā)送郵件實(shí)例講解(python發(fā)郵件附件可以使用email模塊實(shí)現(xiàn))
這篇文章主要介紹了使用Python email模塊、smtplib庫發(fā)送郵件的實(shí)例,大家參考使用2013-12-12

