VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > 编程开发 > python教程 >
  • python基础教程之Python 官方文档 中文版 5. Data Structures

本站最新发布   Python从入门到精通|Python基础教程
试听地址  
https://www.xin3721.com/eschool/pythonxin3721/


数据结构

这一章对你已经学习过的内容进行深入探讨,并且会加入一些新的内容。

5.1 More on Lists

list 数据类型还有一些方法。下列是 list 对象的所有方法:

list.append(x)

​ 在列表末尾添加一个项。等价于 a[len(a):] = [x]

list.extend(iterable)

​ 将 iterable 中所有的项都加到列表中。等价于 a[len(a):] = iterable

list.insert(i, x)

​ 在指定位置插入一个项。第一个参数是要插入的位置的索引,因此 a.insert(0, x) 在列表头部进行插入,a.insert(len(a), x) 等价于 a.append(x)

list.remove(x)

​ 移除列表中第一个值为 x 的项。如果不存在值为 x 的项,会抛出 ValueError 异常。

list.pop([i])

​ 移除并返回指定位置的项。如果没有指定索引,a.pop 移除并返回列表的最后一个项。(在方法签名中 i 周围的方括号表示这个参数是可选的,不是让你把方括号也一起敲入。在Python Library Reference 中你会经常见到这些方括号。)

list.clear()

​ 移除列表中所有的项。等价于 del a[:]

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

​ 返回第一个值为 x 的项的索引(以零为基准)。如果列表中不存在这样的 x,抛出 ValueError 异常。

​ 可选参数 start 和 end 被解释为切片表示法,并且用于将搜索范围缩小为一个列表的特定子序列。index() 方法返回的索引是从整个序列的开头开始计数的,而不是以 start 为头开始计数的。

list.count(x)

​ 返回 x 在列表中出现的次数。

list.sort(key=None, reverse=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 中所有可变数据结构的一个设计原则。

可能你还注意到了不是所有数据都可以被排序或者比较的。比如,[None, 'hello', 10] 不能进行排序,因为 integer 不能和 string 进行比较,None 不能和其他类型进行比较。还有,有些类型没有被定义顺序关系。比如,3+4j < 5+7j 不属于合法的比较。

5.1.1. 把列表当作栈来使用

列表的方法使得列表作为栈(stack)来使用变得非常简单,最后添加的元素就是最先取出的元素(后进先出)。想要在栈顶添加元素,就用 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. 将列表作为队列来使用

还可以将列表作为队列来使用,最先添加的元素会被最先取出(先进先出)。但是,用列表实现的队列并不高效。列表尾部的插入和弹出操作可以很快的进行,但在列表头部进行的插入和弹出操作却很慢(因为所有插入位置后的元素都必须移动一个单位)。

要想实现队列,就使用 collection.deque,它被设计成可以快速地对两端进行 append 和 pop 操作。例如:

>>> 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 comprehension)提供了创建列表的简洁方法。一般用于创建新列表,新列表中每个元素都是将一些运算作用于另一个 sequence 或者 iterable 中的元素后产生的结果;或者用于创建这些元素的满足特定条件的子序列。

比如,假设我们想要创建一个平方数的列表:

>>> 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 子句,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)]

注意,在这两个代码片段中,for 和 if 语句的顺序是相同的。

如果表达式是一个 tuple(如,前面例子中的 (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']
5.1.4. 嵌套的列表推导式

列表推导式中的初始化表达式可以是任何表达式,包括列表推导式。

考虑下面这个 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]]

正如我们在上一节看到的,the nested listcomp is evaluated in the context of the for that follows it#TODO 所以上面的例子等同于:

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

有关这一行中星号的更多内容,请看Unpacking Argument Lists。

5.2. del 语句 ✔

有一种方式可以使用列表的索引,而不是元素值来删除列表的元素:del 语句。del 语句与有返回值的 pop() 方法不同。del 语句还可用于移除列表的切片或者清空整个列表(之前我们将一个空列表赋值给切片来清空列表):

>>> a = [-1, 1, 66.25, 333, 333, 1234.5]
>>> del a[0]
>>> a
[1, 66.25, 333, 333, 1234.5]
>>> del a[2:4]
>>> a
[1, 66.25, 1234.5]
>>> del a[:]
>>> a
[]

del 还可以用于删除一个变量:

>>> del a

此后引用变量 a 将会产生错误(至少在赋新的值给它前是这样)。后面我们会研究 def 的更多用途。

5.3. Tuples 和 Sequences ✔

我们可以看到 list 和 string 有许多共通的地方,比如索引操作和切片操作。它们是 sequance 类型的两个例子(见Sequence Types — list, tuple, range)。因为 Python 还在不断发展,所以其他的数据类型可能会被加入到 Python 中。还有一种标准的 sequence 数据类型:tuple

一个 tuple 由用逗号分隔的一些值组成,如:

>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345
>>> t
(12345, 54321, 'hello!'
      



  
相关教程