Python數據結構(一)

5. Data Structures

This chapter describes some things you’ve learned about already in more detail, and adds some new things as well.html

這一章節將更詳細的描述你已經學到的東西,並增長一些知識。python

5.1. More on Lists

The list data type has some more methods. Here are all of the methods of list objects:express

列表數據類型有不少方法,這裏列出了列表對象的一下方法:app

list. append ( x )

Add an item to the end of the list. Equivalent to a[len(a):] = [x].ide

在列表的尾部增長一個元素,至關於 a[len(a):] = [x]。函數

list. extend ( L )

Extend the list by appending all the items in the given list. Equivalent to a[len(a):] = L.oop

在列表的尾部增長另外一個列表的全部元素,至關於 a[len(a):] = L。ui

list. insert ( i, x )

Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).this

在指定的位置增長一個元素,第一個參數是插入元素的索引,也就是在該元素以前插入元素x。所以a.insert(0,x)就是在第一個元素前插入x。 a.insert(len(a),x)至關於a.append(x)。lua

list. remove ( x )

Remove the first item from the list whose value is x. It is an error if there is no such item.

移除列表中第一個值等於x的元素,若是找不到值爲x的元素,則返回錯誤。

list. pop ( [i])

Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.)

移除列表中指定位置的元素,並返回該元素。若是沒有指定索引,a.pop()移除最後一個元素,並返回該元素。(中括號表示該參數是可選的,而不是說必定得指定索引。你將會在Python庫參考中常常看到這種符號。)

list. clear ( )

Remove all items from the list. Equivalent to del a[:].

移除列表中的全部元素,至關於 del a[:]

list. index ( x )

Return the index in the list of the first item whose value is x. It is an error if there is no such item.

返回列表中第一個值爲x的索引,若是沒有該值,則返回錯誤。

list. count ( x )

Return the number of times x appears in the list.

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

list. sort ( )

Sort the items of the list in place.

給列表中的元素排序。

list. reverse ( )

Reverse the elements of the list in place.

反轉列表中的元素。

list. copy ( )

Return a shallow copy of the list. Equivalent to a[:].

返回列表的拷貝,至關於返回 a[:]。

An example that uses most of the list methods:

該例子使用了列表的大部分方法:

>>> a = [66.25, 333, 333, 1, 1234.5]
>>> print(a.count(333), a.count(66.25), a.count('x'))
2 1 0
>>> a.insert(2, -1)
>>> a.append(333)
>>> a
[66.25, 333, -1, 333, 1, 1234.5, 333]
>>> a.index(333)
1
>>> a.remove(333)
>>> a
[66.25, -1, 333, 1, 1234.5, 333]
>>> a.reverse()
>>> a
[333, 1234.5, 1, 333, -1, 66.25]
>>> a.sort()
>>> a
[-1, 1, 66.25, 333, 333, 1234.5]
>>> a.pop()
1234.5
>>> a
[-1, 1, 66.25, 333, 333]

You might have noticed that methods like insert, remove or sort that only modify the list have no return value printed – they return the default None. [1] This is a design principle for all mutable data structures in Python.

你可能已經注意到像insert,remove或sort方法僅僅只是修改列表但不返回任何值,其實他們都默認返回None。這是全部在Python中可變數據類型的設計原則。

5.1.1. Using Lists as Stacks

The list methods make it very easy to use a list as a stack, where the last element added is the first element retrieved (「last-in, first-out」). To add an item to the top of the stack, use append(). To retrieve an item from the top of the stack, use pop() without an explicit index. For example:

列表的方法使得列表能夠很容易做爲一個堆棧。在堆棧中增長一個元素,能夠使用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]

 

5.1.2. Using Lists as Queues

It is also possible to use a list as a queue, where the first element added is the first element retrieved (「first-in, first-out」); however, lists are not efficient for this purpose. While appends and pops from the end of list are fast, doing inserts or pops from the beginning of a list is slow (because all of the other elements have to be shifted by one).

列表也能夠做爲隊列來使用。然而它做爲隊列可能不是頗有效率。在列表的尾部增長或移除元素很快,但在列表的頭部插入或移除元素很慢(由於全部的元素都要往前移動一位)。

To implement a queue, use collections.deque which was designed to have fast appends and pops from both ends. For example:

要實現隊列,能夠使用collection.deque。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'])

 

5.1.3. List Comprehensions

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.

List comprehensions提供了一個簡潔的方式來建立列表。通常程序經常經過操做另外一個序列或可迭代對象,而後將這些這些返回的元素來做爲列表的元素,或者是建立這些元素的子列表。

For example, assume we want to create a list of squares, like:

例如:假設咱們想建立一個存儲元素平方計算後的的列表:

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

 

 Note that this creates (or overwrites) a variable named x that still exists after the loop completes. We can calculate the list of squares without any side effects using:

注意,當循環結束後,變量x仍然存在。

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

or, equivalently:

或者,至關於:

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

which is more concise and readable.

這種表達式更加簡單和可讀性。

A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it. For example, this listcomp combines the elements of two lists if they are not equal:

這個List comprehensions包括以下一個部分,首先是方括號括起來,方括號中包含一個for子句,後面也能夠有0個或多個for或if子句。經過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)]

Note how the order of the for and if statements is the same in both these snippets.

這兩個代碼片斷中,for語句和if語句的順序是相同的。

If the expression is a tuple (e.g. the (x, y) in the previous example), it must be parenthesized.

一個表達式是個元組(好比上一個例子中的(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]

5.1.4. Nested List Comprehensions

The initial expression in a list comprehension can be any arbitrary expression, including another list comprehension.

 

Consider the following example of a 3x4 matrix implemented as a list of 3 lists of length 4:

看看下面的例子,一個3 x 4的矩陣用一個列表表示:這個列表包含3個子列表,每一個子列表含有4個元素。

>>> matrix = [
...     [1, 2, 3, 4],
...     [5, 6, 7, 8],
...     [9, 10, 11, 12],
... ]

The following list comprehension will transpose rows and columns:

下面的List comprehensions將會對調矩陣的行和列:

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

As we saw in the previous section, the nested listcomp is evaluated in the context of the for that follows it, so this example is equivalent to:

正如咱們上面所看到的,這個例子至關於:

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

which, in turn, is the same as:

一樣也能夠是這種形式:

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

In the real world, you should prefer built-in functions to complex flow statements. The zip() function would do a great job for this use case:

在實際的編寫過程當中,你應該使用內置的函數來實現。zip()函數很是適宜作這樣的事情:

>>> list(zip(*matrix))
[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
相關文章
相關標籤/搜索