python3測試工具開發快速入門教程2數據結構3列表

快速入門

Python有一些複合數據類型,用於組合值。最常用的是 list(列表)),爲中括號之間的逗號分隔的值。列表的元素可以是多種類型,但是通常是同一類型。

>>> squares = [1, 4, 9, 16, 25]
>>> squares
[1, 4, 9, 16, 25]

像字符串和其他序列類型,列表可支持切片和索引:

>>> squares[0]  # indexing returns the item
1
>>> squares[-1]
25
>>> squares[-3:]  # slicing returns a new list
[9, 16, 25]

切片返回新的列表,下面操作返回列表a的淺拷貝:

>>> squares[:]
[1, 4, 9, 16, 25]

列表還支持連接:

>>> squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

字符串是不可改變的,列表是可變的。

>>> cubes = [1, 8, 27, 65, 125]  # something's wrong here
>>> 4 ** 3  # the cube of 4 is 64, not 65!
64
>>> cubes[3] = 64  # replace the wrong value
>>> cubes
[1, 8, 27, 64, 125]

append()方法可以添加元素到尾部:

>>> cubes.append(216)  # add the cube of 6
>>> cubes.append(7 ** 3)  # and the cube of 7
>>> cubes
[1, 8, 27, 64, 125, 216, 343]

也可以對切片賦值,此操作甚至可以改變列表的尺寸,或清空它:

>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> # replace some values
>>> letters[2:5] = ['C', 'D', 'E']
>>> letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
>>> # now remove them
>>> letters[2:5] = []
>>> letters
['a', 'b', 'f', 'g']
>>> # clear the list by replacing all the elements with an empty list
>>> letters[:] = []
>>> letters
[]

內置函數 len() 同樣適用於列表:

>>> letters = ['a', 'b', 'c', 'd']
>>> len(letters)
4

支持嵌套列表(包含其它列表的列表),例如:

>>> a = ['a', 'b', 'c']
>>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
[['a', 'b', 'c'], [1, 2, 3]]
>>> x[0]
['a', 'b', 'c']
>>> x[0][1]
'b'

深入列表

列表的所有方法如下:

方法 功能
list.append(x) 附加元素到列表末端,相當於a[len(a):] = [x]。
list.extend(L) 附加列表L的內容到當前列表後面,相當於 a[len(a):] = L 。
list.insert(i, x) 在指定位置i插入x。i表示插入位置,原來的i位置如果有元素則往後移動一個位置,例如 a.insert(0, x)會插入到列表首部,而a.insert(len(a), x)相當於a.append(x)。
list.remove(x) 刪除列表中第一個值爲x的元素。如果沒有就報錯。
list.pop([i]) 刪除列表指定位置的元素,並將其返回該元素。如果沒有指定索引針對最後一個元素。方括號表示i是可選的。
list.clear() 從列表中刪除所有元素。相當於 del a[:]
list.index(x[, start[, end]]) 返回第一個值爲x的元素的索引。如果沒有則報錯。
list.count(x) 返回x在列表中出現的次數。
list.sort(cmp=None, key=None, reverse=False) 就地對列表中的元素進行排序。
list.reverse() 就地反轉元素。
list.copy() 返回列表的淺拷貝。等同於 a[:]。

實例:

>>> fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
>>> fruits.count('apple')
2
>>> fruits.count('tangerine')
0
>>> fruits.index('banana')
3
>>> fruits.index('banana', 4)  # Find next banana starting a position 4
6
>>> fruits.reverse()
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']
>>> fruits.append('grape')
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']
>>> fruits.sort()
>>> fruits
['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']
>>> fruits.pop()
'pear'

也許大家會發現像insert、remove或者 sort這些修改列表的方法沒有打印返回值–它們返回 None參考。 這是所有可變的數據類型的統一的設計原則。

  • 把鏈表當作堆棧使用

堆棧後進先出。進使用append(),出使用pop()。例如:

>>> 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]
  • 把列表當作隊列使用

列表先進先出。列表頭部插入或者刪除元素的效率並不高,因爲其他相關元素需要移動,建議使用collections.deque。

>>> from collections import 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'])

列表推導式

列表推導(表達)式可以快捷地創建列表。用於基於列表元素(可以附加條件)創建列表。

傳統方式:

>>> squares = []
>>> for x in range(10):
...     squares.append(x**2)
...
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

列表推導:

squares = [x**2 for x in range(10)]

等價於 squares = map(lambda x: x**2, range(10)),但可讀性更好、更簡潔。

列表推導式包含在放括號中,表達式後有for子句,之後可以有零或多個 for 或 if 子句。結果是基於表達式計算出來的列表:

>>> [(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)]

等同於:

>>> combs = []
>>> for x in [1,2,3]:
...     for y in [3,1,4]:
...         if x != y:
...             combs.append((x, y))
...
>>> combs
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

如果想要得到元組 (例如,上例的 (x, y)),必須在表達式要加上括號:

>>> vec = [-4, -2, 0, 2, 4]
>>> # create a new list with the values doubled
>>> [x*2 for x in vec]
[-8, -4, 0, 4, 8]
>>> # filter the list to exclude negative numbers
>>> [x for x in vec if x >= 0]
[0, 2, 4]
>>> # apply a function to all the elements
>>> [abs(x) for x in vec]
[4, 2, 0, 2, 4]
>>> # call a method on each element
>>> freshfruit = ['  banana', '  loganberry ', 'passion fruit  ']
>>> [weapon.strip() for weapon in freshfruit]
['banana', 'loganberry', 'passion fruit']
>>> # create a list of 2-tuples like (number, square)
>>> [(x, x**2) for x in range(6)]
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
>>> # the tuple must be parenthesized, otherwise an error is raised
>>> [x, x**2 for x in range(6)]
  File "<stdin>", line 1, in ?
    [x, x**2 for x in range(6)]
               ^
SyntaxError: invalid syntax
>>> # flatten a list using a listcomp with two 'for'
>>> vec = [[1,2,3], [4,5,6], [7,8,9]]
>>> [num for elem in vec for num in elem]
[1, 2, 3, 4, 5, 6, 7, 8, 9]

列表推導式可使用複雜的表達式和嵌套函數:

>>> from math import pi
>>> [str(round(pi, i)) for i in range(1, 6)]
['3.1', '3.14', '3.142', '3.1416', '3.14159']
  • 嵌套列表推導式

有如下嵌套列表:

>>> 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]]

等同於:

>>> transposed = []
>>> for i in range(4):
...     transposed.append([row[i] for row in matrix])
...
>>> transposed
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

也等同於:

>>> transposed = []
>>> for i in range(4):
...     # the following 3 lines implement the nested listcomp
...     transposed_row = []
...     for row in matrix:
...         transposed_row.append(row[i])
...     transposed.append(transposed_row)
...
>>> transposed
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

zip()內置函數更好:

>>> list(zip(*matrix))
[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
  • 小結:創建列表的常用方法:

1,中括號:比如data = [4, 9, 2, 8, 3, 2, 5, 4, 2]
2,range:比如list(range(100))
3, 列表推導式:比如[expression for variable in sequence],實際是中括號的變種。

列表相關的內置函數len、max、min、sum、sorted、list,請在內置函數中學習。後面的習題會覆蓋這些函數。

參考資料

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章