在python所有的資料結構中,list具有重要地位,並且非常的方便,這篇文章主要是講解list列表的高階應用,基礎知識可以檢視部落格。
此文章為python英文文件的翻譯版本,你也可以檢視英文版。https://docs.python.org/2/tutorial/datastructures.html
use a list as a stack: #像棧一樣使用列表
stack = [3, 4, 5]
stack.append(6)
stack.append(7)
stack
[3, 4, 5, 6, 7]
stack.pop() #刪除最後一個物件
7
stack
[3, 4, 5, 6]
stack.pop()
6
stack.pop()
5
stack
[3, 4]
use a list as a queue: #像佇列一樣使用列表
1 2 3 4 5 6 7 8 9 10 |
> from collections import deque #這裡需要使用模組deque > queue = deque(["Eric", "John", "Michael"]) > queue.append("Terry") # Terry arrives > queue.append("Graham") # Graham arrives > queue.popleft() # The first to arrive now leaves 'Eric' > queue.popleft() # The second to arrive now leaves 'John' > queue # Remaining queue in order of arrival deque(['Michael', 'Terry', 'Graham']) |
three built-in functions: 三個重要的內建函式
filter(), map(), and reduce().
filter(function, sequence)::
按照function函式的規則在列表sequence中篩選資料
1 2 3 4 |
> def f(x): return x % 3 == 0 or x % 5 == 0 ... #f函式為定義整數物件x,x性質為是3或5的倍數 > filter(f, range(2, 25)) #篩選 [3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24] |
map(function, sequence):
map函式實現按照function函式的規則對列表sequence做同樣的處理,
這裡sequence不侷限於列表,元組同樣也可。
1 2 3 4 |
> def cube(x): return x*x*x #這裡是立方計算 還可以使用 x**3的方法 ... > map(cube, range(1, 11)) #對列表的每個物件進行立方計算 [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000] |
注意:這裡的引數列表不是固定不變的,主要看自定義函式的引數個數,map函式可以變形為:def func(x,y) map(func,sequence1,sequence2) 舉例:
1 2 3 4 5 |
seq = range(8) #定義一個列表 > def add(x, y): return x+y #自定義函式,有兩個形參 ... > map(add, seq, seq) #使用map函式,後兩個引數為函式add對應的運算元,如果列表長度不一致會出現錯誤 [0, 2, 4, 6, 8, 10, 12, 14] |
reduce(function, sequence):
reduce函式功能是將sequence中資料,按照function函式操作,如 將列表第一個數與第二個數進行function操作,得到的結果和列表中下一個資料進行function操作,一直迴圈下去…
舉例:
1 2 3 4 |
def add(x,y): return x+y ... reduce(add, range(1, 11)) 55 |
List comprehensions:
這裡將介紹列表的幾個應用:
squares = [x**2 for x in range(10)]
#生成一個列表,列表是由列表range(10)生成的列表經過平方計算後的結果。
[(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
#[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)] 這裡是生成了一個列表,列表的每一項為元組,每個元組是由x和y組成,x是由列表[1,2,3]提供,y來源於[3,1,4],並且滿足法則x!=y。
Nested List Comprehensions:
這裡比較難翻譯,就舉例說明一下吧:
1 2 3 4 5 6 7 |
matrix = [ #此處定義一個矩陣 ... [1, 2, 3, 4], ... [5, 6, 7, 8], ... [9, 10, 11, 12], ... ] [[row[i] for row in matrix] for i in range(4)] #[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]] |
這裡兩層巢狀比較麻煩,簡單講解一下:對矩陣matrix,for row in matrix來取出矩陣的每一行,row[i]為取出每行列表中的第i個(下標),生成一個列表,然後i又是來源於for i in range(4) 這樣就生成了一個列表的列表。
The del statement:
刪除列表指定資料,舉例:
1 2 3 4 5 6 7 8 9 10 |
> a = [-1, 1, 66.25, 333, 333, 1234.5] >del a[0] #刪除下標為0的元素 >a [1, 66.25, 333, 333, 1234.5] >del a[2:4] #從列表中刪除下標為2,3的元素 >a [1, 66.25, 1234.5] >del a[:] #全部刪除 效果同 del a >a [] |
Sets: 集合
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] >>> fruit = set(basket) # create a set without duplicates >>> fruit set(['orange', 'pear', 'apple', 'banana']) >>> 'orange' in fruit # fast membership testing True >>> 'crabgrass' in fruit False >>> # Demonstrate set operations on unique letters from two words ... >>> a = set('abracadabra') >>> b = set('alacazam') >>> a # unique letters in a set(['a', 'r', 'b', 'c', 'd']) >>> a - b # letters in a but not in b set(['r', 'd', 'b']) >>> a | b # letters in either a or b set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l']) >>> a & b # letters in both a and b set(['a', 'c']) >>> a ^ b # letters in a or b but not both set(['r', 'd', 'b', 'm', 'z', 'l']) |
Dictionaries:字典
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
>>> tel = {'jack': 4098, 'sape': 4139} >>> tel['guido'] = 4127 #相當於向字典中新增資料 >>> tel {'sape': 4139, 'guido': 4127, 'jack': 4098} >>> tel['jack'] #取資料 4098 >>> del tel['sape'] #刪除資料 >>> tel['irv'] = 4127 #修改資料 >>> tel {'guido': 4127, 'irv': 4127, 'jack': 4098} >>> tel.keys() #取字典的所有key值 ['guido', 'irv', 'jack'] >>> 'guido' in tel #判斷元素的key是否在字典中 True >>> tel.get('irv') #取資料 4127 |
也可以使用規則生成字典:
1 2 |
>>> {x: x**2 for x in (2, 4, 6)} {2: 4, 4: 16, 6: 36} |
enumerate():遍歷元素及下標
enumerate 函式用於遍歷序列中的元素以及它們的下標:
1 2 3 4 5 6 |
>>> for i, v in enumerate(['tic', 'tac', 'toe']): ... print i, v ... 0 tic 1 tac 2 toe |
zip():
zip()是Python的一個內建函式,它接受一系列可迭代的物件作為引數,將物件中對應的元素打包成一個個tuple(元組),然後返回由這些tuples組成的list(列表)。若傳入引數的長度不等,則返回list的長度和引數中長度最短的物件相同。利用*號操作符,可以將list unzip(解壓)。
1 2 3 4 5 6 7 8 |
>>> questions = ['name', 'quest', 'favorite color'] >>> answers = ['lancelot', 'the holy grail', 'blue'] >>> for q, a in zip(questions, answers): ... print 'What is your {0}? It is {1}.'.format(q, a) ... What is your name? It is lancelot. What is your quest? It is the holy grail. What is your favorite color? It is blue. |
有關zip舉一個簡單點兒的例子:
1 2 3 4 5 6 7 8 9 |
>>> a = [1,2,3] >>> b = [4,5,6] >>> c = [4,5,6,7,8] >>> zipped = zip(a,b) [(1, 4), (2, 5), (3, 6)] >>> zip(a,c) [(1, 4), (2, 5), (3, 6)] >>> zip(*zipped) [(1, 2, 3), (4, 5, 6)] |
reversed():反轉
1 2 3 4 5 6 7 8 |
>>> for i in reversed(xrange(1,10,2)): ... print i ... 9 7 5 3 1 |
sorted(): 排序
1 2 3 4 5 6 7 8 |
> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] > for f in sorted(set(basket)): #這裡使用了set函式 ... print f ... apple banana orange pear |
python的set和其他語言類似, 是一個 基本功能包括關係測試和消除重複元素.
To change a sequence you are iterating over while inside the loop (for example to duplicate certain items), it is recommended that you first make a copy. Looping over a sequence does not implicitly make a copy. The slice notation makes this especially convenient:
1 2 3 4 5 6 7 |
>>> words = ['cat', 'window', 'defenestrate'] >>> for w in words[:]: # Loop over a slice copy of the entire list. ... if len(w) > 6: ... words.insert(0, w) ... >>> words ['defenestrate', 'cat', 'window', 'defenestrate'] |