数据结构-元组-列表-字典(5)python入门教程
本章更详细地描述了您已经了解的一些内容,并添加了一些新内容。
5.1 更多关于列表
list.
insert(i, x)
- 在给定位置插入一个项目。第一个参数是要插入之前的元素的索引,因此插入到列表的前面,相当于.
a.insert(0, x)
a.insert(len(a), x)
a.append(x)
list.
remove(x)
- 从列表中删除值等于x的第一项。
ValueError
如果没有这样的项目,它会引发 a 。
list.
pop([i])
- 删除列表中给定位置的项目,并将其返回。如果未指定索引,则
a.pop()
删除并返回列表中的最后一项。(方法签名中i周围的方括号表示该参数是可选的,而不是您应该在该位置键入方括号。您将在 Python 库参考中经常看到这种表示法。)
list.
clear()
- 从列表中删除所有项目。相当于。
del a[:]
list.
index(x[, start[, end]])
- 返回值等于x的第一项的列表中从零开始的索引。
ValueError
如果没有这样的项目,则引发 a 。可选参数start和end被解释为切片符号,用于将搜索限制为列表的特定子序列。返回的索引是相对于完整序列的开头而不是start参数计算的。
list.
count(x)
- 返回x在列表中出现的次数。
list.
reverse=Falsesort(key=None,
)
- 就地对列表中的项目进行排序(参数可用于排序自定义,请参阅
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'
你可能已经注意到,像insert
,remove
或者sort
只修改列表的方法没有打印返回值——它们返回默认值 None
。这是 Python 中所有可变数据结构的设计原则。
5.1.1 使用列表作为堆栈
list 方法可以很容易地将列表用作堆栈,其中添加的最后一个元素是检索到的第一个元素(“后进先出”)。要将项目添加到堆栈顶部,请使用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 使用列表作为队列
也可以将列表用作队列,其中添加的第一个元素是检索到的第一个元素(“先进先出”);但是,列表对此目的无效。虽然从列表末尾追加和弹出很快,但从列表开头插入或弹出很慢(因为所有其他元素都必须移动一个)。
为了实现一个队列,使用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'])
5.1.3 列表理解
列表推导式提供了一种创建列表的简洁方式。常见的应用是创建新列表,其中每个元素是应用于另一个序列或可迭代的每个成员的某些操作的结果,或者创建满足特定条件的那些元素的子序列。
例如,假设我们要创建一个正方形列表,例如:
>>>
>>> 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
orif
子句。结果将是一个新列表,该列表是在其后面的for
andif
子句的上下文中评估表达式而产生的。例如,如果两个列表的元素不相等,则此 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)]
请注意,在这两个片段中, for
and语句的顺序是相同的。if
如果表达式是一个元组(例如在前面的例子中),它必须用括号括起来。(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]
列表推导可以包含复杂的表达式和嵌套函数:
>>>
>>> matrix = [
... [1, 2, 3, 4],
... [5, 6, 7, 8],
... [9, 10, 11, 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()
功能对于这个用例非常有用:
>>>
>>> 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
。
5.3 元组和序列
我们看到列表和字符串有许多共同的属性,例如索引和切片操作。它们是序列数据类型的两个示例(请参阅 序列类型 – 列表、元组、范围)。由于 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 "<stdin>", line 1, in <module>
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])
如您所见,输出元组总是用括号括起来,以便正确解释嵌套元组;它们可以带或不带括号输入,尽管通常括号是必需的(如果元组是更大表达式的一部分)。不能分配给元组的各个项目,但是可以创建包含可变对象的元组,例如列表。
尽管元组可能看起来类似于列表,但它们通常用于不同的情况和不同的目的。元组是不可变的,并且通常包含通过解包(参见本节后面部分)或索引(甚至在 的情况下通过属性)访问的异构元素序列namedtuples
。列表是可变的,它们的元素通常是同质的,可以通过遍历列表来访问。
一个特殊的问题是包含 0 或 1 项的元组的构造:语法有一些额外的怪癖来适应这些。空元组由一对空括号构成;一个包含一个项目的元组是通过一个带有逗号的值来构造的(将单个值括在括号中是不够的)。丑陋,但有效。例如:
>>>
>>> empty = ()
>>> singleton = 'hello', # <-- note trailing comma
>>> len(empty)
0
>>> len(singleton)
1
>>> singleton
('hello',)
该语句是元组打包的示例:值,和被打包在一个元组中。反向操作也是可能的:t = 12345, 54321, 'hello!'1234554321'hello!'
>>>
>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>> print(basket) # show that duplicates have been removed
{'orange', 'banana', 'pear', 'apple'}
>>> 'orange' in basket # fast membership testing
True
>>> 'crabgrass' in basket
False
>>> # Demonstrate set operations on unique letters from two words
...
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a # unique letters in a
{'a', 'r', 'b', 'c', 'd'}
>>> a - b # letters in a but not in b
{'r', 'd', 'b'}
>>> a | b # letters in a or b or both
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
>>> a & b # letters in both a and b
{'a', 'c'}
>>> a ^ b # letters in a or b but not both
{'r', 'd', 'b', 'm', 'z', 'l'}
与列表推导类似,也支持集合理解:
>>>
>>> a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
{'r', 'd'}
5.5. 字典
Python 中内置的另一种有用的数据类型是字典(请参阅 映射类型 – dict)。字典有时在其他语言中被称为“关联记忆”或“关联数组”。与由一系列数字索引的序列不同,字典由键索引,它可以是任何不可变类型;字符串和数字总是可以作为键。如果元组仅包含字符串、数字或元组,则元组可以用作键;如果元组直接或间接包含任何可变对象,则不能将其用作键。您不能将列表用作键,因为可以使用索引分配、切片分配或类似的方法修改append()
列表 extend()
。
最好将字典视为一组键:值对,并要求键是唯一的(在一个字典中)。一对大括号创建一个空字典:{}
. 在大括号内放置一个逗号分隔的键:值对列表,将初始键:值对添加到字典中;这也是在输出上编写字典的方式。
字典上的主要操作是存储带有某个键的值并提取给定键的值。也可以使用 删除键:值对del
。如果您使用已在使用的密钥进行存储,则与该密钥关联的旧值将被遗忘。使用不存在的键提取值是错误的。
对字典执行list(d)
会返回字典中使用的所有键的列表,按插入顺序排列(如果要对其进行排序,只需使用 sorted(d)
)。要检查字典中是否有单个键,请使用in
关键字。
这是一个使用字典的小例子:
>>>
>>> tel = {'jack': 4098, 'sape': 4139}
>>> tel['guido'] = 4127
>>> tel
{'jack': 4098, 'sape': 4139, 'guido': 4127}
>>> tel['jack']
4098
>>> del tel['sape']
>>> tel['irv'] = 4127
>>> tel
{'jack': 4098, 'guido': 4127, 'irv': 4127}
>>> list(tel)
['jack', 'guido', 'irv']
>>> sorted(tel)
['guido', 'irv', 'jack']
>>> 'guido' in tel
True
>>> 'jack' not in tel
False
构造dict()
函数直接从键值对序列构建字典:
>>>
>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
{'sape': 4139, 'guido': 4127, 'jack': 4098}
此外,dict 推导式可用于从任意键和值表达式创建字典:
>>>
>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}
当键是简单字符串时,有时使用关键字参数指定对更容易:
>>>
>>> dict(sape=4139, guido=4127, jack=4098)
{'sape': 4139, 'guido': 4127, 'jack': 4098}
5.6 循环技术
items()
在遍历字典时,可以使用该方法同时检索键和对应的值。
>>>
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.items():
... print(k, v)
...
gallahad the pure
robin the brave
enumerate()
循环遍历一个序列时,可以使用该函数同时检索位置索引和对应的值。
>>>
>>> for i, v in enumerate(['tic', 'tac', 'toe']):
... print(i, v)
...
0 tic
1 tac
2 toe
要同时循环两个或多个序列,条目可以与zip()
函数配对。
>>>
>>> questions = ['name', 'quest', 'favorite color']
>>> answers = ['lancelot', 'the holy grail', 'blue']
>>> for q, a in zip(questions, answers):
... print('What is your {0}? It is {1}.'.format(q, a))
...
What is your name? It is lancelot.
What is your quest? It is the holy grail.
What is your favorite color? It is blue.
要反向循环序列,首先在正向指定序列,然后调用该reversed()
函数。
>>>
>>> for i in reversed(range(1, 10, 2)):
... print(i)
...
9
7
5
3
1
要按排序顺序循环序列,请使用sorted()
返回新排序列表的函数,同时保持源不变。
>>>
>>> import math
>>> raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8]
>>> filtered_data = []
>>> for value in raw_data:
... if not math.isnan(value):
... filtered_data.append(value)
...
>>> filtered_data
[56.2, 51.7, 55.3, 52.5, 47.8]
5.7 更多关于条件
while
and语句中使用的条件if
可以包含任何运算符,而不仅仅是比较。
比较运算符in
并检查一个值是否在序列中出现(不出现)。运算符和比较两个对象是否真的是同一个对象;这只对像列表这样的可变对象很重要。所有比较运算符的优先级相同,低于所有数值运算符的优先级。not in
is
is not
比较可以链接。例如,测试是否小于和等于。a < b == c
a
b
b
c
可以使用布尔运算符and
和组合比较or
,并且可以用 来否定比较(或任何其他布尔表达式)的结果not
。它们的优先级低于比较运算符;在它们之间,not
具有最高优先级和or
最低优先级,因此相当于. 与往常一样,括号可用于表示所需的组合。A and not B or C
(A and (not B)) or C
布尔运算符and
和or
是所谓的短路 运算符:它们的参数从左到右进行评估,一旦确定结果,评估就会停止。例如,如果A
和C
为真但B
为假,则不计算表达式 。当用作一般值而不是布尔值时,短路运算符的返回值是最后评估的参数。A and B and C
C
可以将比较结果或其他布尔表达式分配给变量。例如,
>>>
>>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
>>> non_null = string1 or string2 or string3
>>> non_null
'Trondheim'
=
表达式。==
5.8 比较序列和其他类型
序列对象可以与具有相同序列类型的其他对象进行比较。比较使用字典顺序:首先比较前两项,如果它们不同,则确定比较的结果;如果它们相等,则比较接下来的两项,依此类推,直到任一序列用完。如果要比较的两个项目本身是相同类型的序列,则以递归方式进行字典比较。如果两个序列的所有项比较相等,则认为序列相等。如果一个序列是另一个序列的初始子序列,则较短的序列是较小(较小)的序列。字符串的字典顺序使用 Unicode 代码点编号对单个字符进行排序。相同类型序列之间比较的一些示例:
(1, 2, 3) < (1, 2, 4)
[1, 2, 3] < [1, 2, 4]
'ABC' < 'C' < 'Pascal' < 'Python'
(1, 2, 3, 4) < (1, 2, 4)
(1, 2) < (1, 2, -1)
(1, 2, 3) == (1.0, 2.0, 3.0)
(1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)
请注意,如果对象具有适当的比较方法,则将不同类型的对象与<
or进行比较是合法的。>
例如,混合数字类型根据它们的数值进行比较,因此 0 等于 0.0 等。否则,解释器将引发TypeError
异常,而不是提供任意顺序。