標籤:comm 反向 ber seq view pos img value pes
列表是以類的形式實現的。
“建立”列表實際上是將一個類執行個體化。
因此,列表有多種方法能夠操作。
Python列表操作的函數和方法
1、cmp(list1, list2):比較兩個列表的元素
2、len(list):列表元素個數
3、max(list):返回列表元素最大值
4、min(list):返回列表元素最小值
5、list(seq):將元群組轉換為列表
1、list.append(obj):在列表末尾加入新的對象
2、list.count(obj):統計某個元素在列表中出現的次數
3、list.extend(seq):在列表末尾一次性追加還有一個序列中的多個值(用新列表擴充原來的列表)
4、list.index(obj):從列表中找出某個值第一個匹配項的索引位置
5、list.insert(index, obj):將對象插入列表
6、list.pop(obj=list[-1]):移除列表中的一個元素(預設最後一個元素)。而且返回該元素的值
7、list.remove(obj):移除列表中某個值的第一個匹配項
8、list.reverse():反向列表中元素
9、list.sort([func]):對原列表進行排序
>>> #list.append(n),追加元素,僅僅接收一個參數>>> a[0, 1, 2, 3, 4, 5, 6, 7]>>> a.append(6)>>> a[0, 1, 2, 3, 4, 5, 6, 7, 6]
>>> #list.count(n) , 計算n在list中出現的次數>>> a[0, 1, 2, 3, 4, 5, 6, 7, 6]>>> a.count(6)2
>>> #list.extend(list1) , 將list1追加到list的後面>>> a[0, 1, 2, 3, 4, 5, 6, 7, 6]>>> b = [‘a‘ , ‘b‘ , ‘c‘ , ‘d‘]>>> a[0, 1, 2, 3, 4, 5, 6, 7, 6]>>> a.extend(b)>>> a[0, 1, 2, 3, 4, 5, 6, 7, 6, ‘a‘, ‘b‘, ‘c‘, ‘d‘]>>> a.append(b) #能夠注意append與extend的差別>>> a[0, 1, 2, 3, 4, 5, 6, 7, 6, ‘a‘, ‘b‘, ‘c‘, ‘d‘, [‘a‘, ‘b‘, ‘c‘, ‘d‘]]
>>> #list.index(n) , 返回n在list中的位置,若無,則拋出異常>>> a[0, 1, 2, 3, 4, 5, 6, 7, 6]>>> a.index(‘x‘)Traceback (most recent call last): File "<pyshell#67>", line 1, in <module> a.index(‘x‘)ValueError: ‘x‘ is not in list>>> a.index(4)4
>>> #list.insert(index,var) , 在index出插入var,其餘元素向後推。假設index大於list的長度,就會在後面加入。假設index小於0,就要在最開始出加入>>> a[0, 1, 2, 3, 4, 5, 6, 7, 6, ‘a‘, ‘b‘, ‘c‘, ‘d‘, [‘a‘, ‘b‘, ‘c‘, ‘d‘]]>>> a.insert(0,1)>>> a[1, 0, 1, 2, 3, 4, 5, 6, 7, 6, ‘a‘, ‘b‘, ‘c‘, ‘d‘, [‘a‘, ‘b‘, ‘c‘, ‘d‘]]>>> a.insert(100,100)>>> a[1, 0, 1, 2, 3, 4, 5, 6, 7, 6, ‘a‘, ‘b‘, ‘c‘, ‘d‘, [‘a‘, ‘b‘, ‘c‘, ‘d‘], 100]>>>
>>> #list.pop() , 返回最後一個元素,而且刪除最後一個元素。list.pop(index) , 返回index處的元素,而且刪除該元素。>>> a[1, 0, 1, 2, 3, 4, 5, 6, 7, 6, ‘a‘, ‘b‘, ‘c‘, ‘d‘,100]>>> a.pop()100>>> a[1, 0, 1, 2, 3, 4, 5, 6, 7, 6, ‘a‘, ‘b‘, ‘c‘, ‘d‘,]>>> a.pop(0)1>>> a[0, 1, 2, 3, 4, 5, 6, 7, 6, ‘a‘, ‘b‘, ‘c‘, ‘d‘]
>>> #list.remove(var) , 找到var而且刪除它。若無,則拋出異常>>> a[0, 1, 2, 3, 4, 5, 6, 7, 6, ‘a‘, ‘b‘, ‘c‘, ‘d‘]>>> a.remove(9)Traceback (most recent call last): File "<pyshell#98>", line 1, in <module> a.remove(9)ValueError: list.remove(x): x not in list>>> a.remove(6)>>> a[0, 1, 2, 3, 4, 5, 7, 6, ‘a‘, ‘b‘, ‘c‘, ‘d‘]
>>> #list.reverse() , 將list倒序>>> a[0, 1, 2, 3, 4, 5, 7, 6, ‘a‘, ‘b‘, ‘c‘, ‘d‘]>>> a.reverse()>>> a[‘d‘, ‘c‘, ‘b‘, ‘a‘, 6, 7, 5, 4, 3, 2, 1, 0]
>>> #list.sort() , 將list進行排序,a中元素若類型不同。結果自己看看一下,可是一般不會這麼做>>> a[‘d‘, ‘c‘, ‘b‘, ‘a‘, 6, 7, 5, 4, 3, 2, 1, 0]>>> a.sort()Traceback (most recent call last): File "<pyshell#107>", line 1, in <module> a.sort()TypeError: unorderable types: int() < str()>>> a = [1,3,2,4,5,6,3,2,1]>>> a[1, 3, 2, 4, 5, 6, 3, 2, 1]>>> a.sort()>>> a[1, 1, 2, 2, 3, 3, 4, 5, 6]
Python學習(五)——列表操作全透析