判斷一個(gè) list 是否為空
傳統(tǒng)的方式:
if len(mylist): # Do something with my listelse: # The list is empty
由于一個(gè)空 list 本身等同于 False,所以可以直接:
if mylist: # Do something with my listelse: # The list is empty
遍歷 list 的同時(shí)獲取索引
傳統(tǒng)的方式:
i = 0for element in mylist: # Do something with i and element i += 1
這樣更簡(jiǎn)潔些:
for i, element in enumerate(mylist): # Do something with i and element pass
list 排序
在包含某元素的列表中依據(jù)某個(gè)屬性排序是一個(gè)很常見(jiàn)的操作。例如這里我們先創(chuàng)建一個(gè)包含 person 的 list:
class Person(object): def __init__(self, age): self.age = agepersons = [Person(age) for age in (14, 78, 42)]
傳統(tǒng)的方式是:
def get_sort_key(element): return element.agefor element in sorted(persons, key=get_sort_key): print "Age:", element.age
更加簡(jiǎn)潔、可讀性更好的方法是使用 Python 標(biāo)準(zhǔn)庫(kù)中的 operator 模塊:
from operator import attrgetterfor element in sorted(persons, key=attrgetter('age')): print "Age:", element.ageattrgetter 方法優(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,追求簡(jiǎn)潔優(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è)問(wèn)題嗎?
找出100以內(nèi)的能夠被3整除的正整數(shù)。
我們用的方法是:
aliquot = []for n in range(1,100): if n%3 == 0: aliquot.append(n)print aliquot
好了。現(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ù),本來(lái)我們可以通過(guò)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 0sunday is 1friday 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 0sunday is 1friday is 2
算是一個(gè)有意思的內(nèi)置函數(shù)了,主要是提供一個(gè)簡(jiǎn)單快捷的方法。
官方文檔是這么說(shuō)的:
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')]
新聞熱點(diǎn)
疑難解答
圖片精選