Python之列表list模块
一、基礎
1.常用方法:【'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'這些方法,下面進行講解】
1)append在列表的最后添加,如果為可迭代元素,則可迭代元素作為整體添加到列表
2)extend在列表的最后添加;如果為可迭代元素, 則把可迭代元素分開添加到列表
3)默認刪除列表中的最后一個元素pop,也可以根據元素的位置刪除列表元素
4)remove根據列表值的內容刪除某個列表元素
5)reverse反轉列表
6)給列表排序sort
二、進階
1、判斷一個 list 是否為空
傳統的方式:
if len(mylist):# Do something with my list else:# The list is empty由于一個空 list 本身等同于 False,所以可以直接:
if mylist:# Do something with my list else:# The list is empty2、遍歷 list 的同時獲取索引
傳統的方式:
i = 0 for element in mylist:# Do something with i and elementi += 1這樣更簡潔些:Python提供了一個內置的enumerate函數,可以把一個list變成索引-元素對,這樣就可以做到在for循環中迭代索引和元素本身。
for i, element in enumerate(mylist):# Do something with i and elementpass3、list 排序
在包含某元素的列表中依據某個屬性排序是一個很常見的操作。例如這里我們先創建一個包含 person 的 list:
class Person(object):def __init__(self, age):self.age = agepersons = [Person(age) for age in (14, 78, 42)]傳統的方式是:
def get_sort_key(element):return element.agefor element in sorted(persons, key=get_sort_key):print "Age:", element.age更加簡潔、可讀性更好的方法是使用 Python 標準庫中的 operator 模塊:
from operator import attrgetterfor element in sorted(persons, key=attrgetter('age')):print "Age:", element.ageattrgetter 方法優先返回讀取的屬性值作為參數傳遞給 sorted 方法。operator 模塊還包括 itemgetter 和 methodcaller 方法,作用如其字面含義。
4、list解析
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好了?,F在用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']5、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 2python中提供了一個內置函數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')]?
總結
以上是生活随笔為你收集整理的Python之列表list模块的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python3 中 random模块
- 下一篇: RabbitMQ—重复消费、数据丢失和消