Python 中的数据结构

本教程是 Python 官方网站上 《Tutorial》 部分文档的翻译,本文档与 官方文档授权一致

本章将详细介绍一些您已经了解的内容,并添加了一些新内容。

1. 列表的更多特性

列表数据类型还有很多的方法。这里是列表对象方法的清单:

list.append(*x*)

在列表的末尾添加一个元素。相当于 a[len(a):] = [x]

list.extend(*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 的元素。如果没有这样的元素,则抛出 ValueError 异常。

list.pop([*i*])

删除列表中给定位置的元素并返回它。如果没有给定位置,a.pop() 将会删除并返回列表中的最后一个元素。(方法签名中 i 两边的方括号表示这个参数是可选的,而不是要你输入方括号。你会在 Python 参考库中经常看到这种表示方法)。

list.clear()

删除列表中所有的元素。相当于 del a[:]

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

返回列表中第一个值为 x 的元素的从零开始的索引。如果没有这样的元素将会抛出 ValueError 异常。

可选参数 start 和 end 是切片符号,用于将搜索限制为列表的特定子序列。返回的索引是相对于整个序列的开始计算的,而不是 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 方法,只修改列表,没有打印出返回值——它们返回默认值 None1 这是 Python 中所有可变数据结构的设计原则。

你可能会注意到的另一件事是并非所有数据或可以排序或比较。例如,[None, 'hello', 10] 就不可排序,因为整数不能与字符串比较,而 None 不能与其他类型比较。并且还存在一些没有定义顺序关系的类型。例如,3+4j < 5+7j 就不是一个合法的比较。

1.1 列表作为栈使用

列表方法使得列表作为堆栈非常容易,最后一个插入,最先取出(“后进先出”)。要添加一个元素到堆栈的顶端,使用 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]

1.2 列表作为队列使用

列表也可以用作队列,其中先添加的元素被最先取出 (“先进先出”);然而列表用作这个目的相当低效。因为在列表的末尾添加和弹出元素非常快,但是在列表的开头插入或弹出元素却很慢 ( 因为所有的其他元素都必须移动一位)。

若要实现一个队列,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'])

1.3 列表推导式

列表推导式提供了一个更简单的创建列表的方法。常见的用法是把某种操作应用于序列或可迭代对象的每个元素上,然后使用其结果来创建列表,或者通过满足某些特定条件元素来创建子序列。

例如,假设我们想创建一个平方列表,像这样

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

注意这里创建(或被重写)的名为 x 的变量在 for 循环后仍然存在。我们可以计算平方列表的值而不会产生任何副作用

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

或者,等价于

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

上面这种写法更加简洁易读。

列表推导式的结构是由一对方括号所包含的以下内容:一个表达式,后面跟一个 for 子句,然后是零个或多个 forif 子句。其结果将是一个新列表,由对表达式依据后面的 forif 子句的内容进行求值计算而得出。举例来说,以下列表推导式会将两个列表中不相等的元素组合起来:

>>> [(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 "", 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']

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

如上节所示,嵌套的列表推导式是基于跟随其后的 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)]

关于本行中星号的详细说明,参见 解包参数列表

2. 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 时会报错(直到另一个值被赋给它)。我们会在后面了解到 del 的其他用法。

3. 元组和序列

我们看到列表和字符串有很多共同特性,例如索引和切片操作。他们是 序列 数据类型(参见 序列类型 --- list, tuple, range)中的两种。随着 Python 语言的发展,其他的序列类型也会被加入其中。这里介绍另一种标准序列类型:元组。

一个元组由几个被逗号隔开的值组成,例如

>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345
>>> t
(12345, 54321, 'hello!')
>>> # Tuples may be nested:
…… u = t, (1, 2, 3, 4, 5)
>>> u
((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
>>> # Tuples are immutable:
…… t[0] = 88888
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'tuple' object does not support item assignment
>>> # but they can contain mutable objects:
…… v = ([1, 2, 3], [3, 2, 1])
>>> v
([1, 2, 3], [3, 2, 1])

如你所见,元组在输出时总是被圆括号包围的,以便正确表示嵌套元组。输入时圆括号可有可无,不过经常会是必须的(如果这个元组是一个更大的表达式的一部分)。给元组中的一个单独的元素赋值是不允许的,当然你可以创建包含可变对象的元组,例如列表。

  • 发表于 · 2022.04.13 08:39 · 阅读 · 517

[版权声明] :本文文字、代码及图片版权归原作者所有,任何媒体、网站或个人未经本网协议授权不得采集、整理、转载或以其他方式复制发表。已经本站协议授权的媒体、网站,在使用时必须注明“稿件来源:学研谷”。

0 条评论

请先 登录 后评论
猜猜我是谁
traveler

10
提问
12
回答
18
文章