Python 3.6 學習-- 基礎5:數據結構--列表。

更多關於列表

列表數據類型有更多方法。以下是列表對象的所有方法:

list.append

將項添加到列表的末尾。相當於。a[len(a):] = [x]

list.extend可迭代的

通過附加iterable中的所有項來擴展列表。相當於 。a[len(a):] = iterable

list.inserti

在給定位置插入項目。第一個參數是要插入的元素的索引,因此插入列表的前面,並且等效於。a.insert(0,x)a.insert(len(a), x)a.append(x)

list.remove

從列表中刪除值爲x的第一個項目。如果沒有這樣的項目則是錯誤的。

list.pop([ ] )

刪除列表中給定位置的項目,然後將其返回。如果未指定索引,則a.pop()刪除並返回列表中的最後一項。(方法簽名中i周圍的方括號表示該參數是可選的,而不是您應該在該位置鍵入方括號。您將在Python Library Reference中經常看到這種表示法。)

list.clear()

從列表中刪除所有項目。相當於。del a[:]

list.index[,start [,end ] ] )

在值爲x的第一個項的列表中返回從零開始的索引。ValueError如果沒有這樣的項目,則提高a 。

可選參數startend被解釋爲切片表示法,並用於將搜索限制爲列表的特定子序列。返回的索引是相對於完整序列的開頭而不是start參數計算的。

list.count

返回x出現在列表中的次數。

list.sortkey = Nonereverse = False 

對列表中的項目進行排序(參數可用於排序自定義,請參閱sorted()其說明)。

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'

 您可能已經注意到,方法一樣insertremove或者sort只修改列表沒有返回值印刷-它們返回的默認 None。 這是Python中所有可變數據結構的設計原則

使用列表作爲堆棧

list方法可以很容易地將列表用作堆棧,其中添加的最後一個元素是檢索到的第一個元素(“last-in,first-out”)。要將項添加到堆棧頂部,請使用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]

 請注意,這會創建(或覆蓋)一個名爲x在循環完成後仍然存在的變量。我們可以使用以下方法計算沒有任何副作用的正方形列表:

squares = list(map(lambda x: x**2, range(10)))

 或者,等效地:

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

這更簡潔,更易讀。

列表推導由括號組成,括號中包含一個表達式,後跟一個for子句,然後是零個或多個forif 子句。結果將是一個新的列表,該列表是通過在其後面的forif子句的上下文中評估表達式而得到的。例如,如果列表不相等,則此listcomp將兩個列表的元素組合在一起:

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

請注意這兩個片段中forif語句的順序是如何相同的。

如果表達式是元組(例如前面示例中的元組),則必須將其括起來。(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 <module>
    [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']

 

嵌套列表理解

列表推導中的初始表達式可以是任意表達式,包括另一個列表推導。

考慮以下3x4矩陣示例,該矩陣實現爲3個長度爲4的列表:

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

 正如我們在上一節中看到的那樣,嵌套的listcomp在其後面的上下文中進行計算for,因此該示例等效於:

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

有關此行中星號的詳細信息,請參閱解壓縮參數列表

 

 

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