数据结构

……

列表更多的内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# list.append(x)  在末尾添加一项
# list.extend(iterable) 在末尾添加iterable的所有项
# list.insert(i, x) 在索引为i的前一项添加内容x
# list.remove(x) 删除内容为x的第一个item
# list.pop([i]) 删除索引为i的item并返回这个item
#a.pop() 删除返回的是最后一项,[]表示可写参数
# list.clear() 删除所有项
# list.index(x[, start[, end]]) 返回内容为x的第一个item的索引
# start,end用于指定范围,可有可无
# list.count(x) 返回x出现的次数
# list.sort(key=None, reverse=False) 由小到大排序,key指定内容
# reverse指定升序还是降序
# list.reverse() 将list反序排一下
# list.copy() 返回一个副本

>>> fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
>>> fruits.count('apple')
2
>>> fruits.count('tangerine')
0
>>> fruits.index('banana')
3
>>> fruits.index('banana', 4) # 从索引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'

用列表模拟堆栈

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
>>> 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
3
4
5
6
7
8
9
10
11
# 并不高效,取出最后一个很快,但取出第一个不快,因为其他元素需要移位一个
>>> from collections import deque
>>> queue = deque(["Eric", "John", "Michael"])
>>> queue.append("Terry")
>>> queue.append("Graham")
>>> queue.popleft()
'Eric'
>>> queue.popleft()
'John'
>>> queue
deque(['Michael', 'Terry', 'Graham'])

列表推导式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
>>> squares = []  # 这是一般的方式
>>> for x in range(10):
... squares.append(x**2)
...
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

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

squares = [x**2 for x in range(10)] # 列表推导式的方式

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

>>> vec = [-4, -2, 0, 2, 4]
>>> [x*2 for x in vec]
[-8, -4, 0, 4, 8]
>>> [x for x in vec if x >= 0]
[0, 2, 4]
>>> [abs(x) for x in vec]
[4, 2, 0, 2, 4]
>>> freshfruit = [' banana', ' loganberry ', 'passion fruit ']
>>> [weapon.strip() for weapon in freshfruit] # 应该是删去空格
['banana', 'loganberry', 'passion fruit']
>>> [(x, x**2) for x in range(6)] # 生成一个元素是元组的列表,注意括号
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
>>> 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
2
3
4
5
6
7
8
9
>>> matrix = [     ## 一个3*4矩阵,包含三个长度为4列表的列表
... [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]]
>>> list(zip(*matrix)) # 使用zip函数
[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]

del语句

1
2
3
4
5
6
7
8
9
10
11
>>> 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 a # 删除变量

元组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
>>> t = 12345, 54321, 'hello!'  # 用逗号隔开
>>> t[0]
12345
>>> t
(12345, 54321, 'hello!')
>>> x, y, z = t # 可以这样分别赋值
>>> u = t, (1, 2, 3, 4, 5) # 像列表一样可以堆叠
>>> u
((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
>>> t[0] = 88888 # 注意不可变
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>>v = ([1, 2, 3], [3, 2, 1]) # 元素可以为列表
>>> v
([1, 2, 3], [3, 2, 1])

>>> empty = ()
>>> singleton = 'hello',
>>> len(empty)
0
>>> len(singleton)
1
>>> singleton
('hello',)

集合

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# 无重复元素,无序
>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>> print(basket)
{'orange', 'banana', 'pear', 'apple'}
>>> 'orange' in basket
True
>>> 'crabgrass' in basket
False

>>> a = set('abracadabra') # 另一种创建方式
>>> b = set('alacazam')
>>> a
{'a', 'r', 'b', 'c', 'd'}
>>> a - b # 在a中不在b中
{'r', 'd', 'b'}
>>> a | b
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
>>> a & b
{'a', 'c'}
>>> a ^ b # 在a或者b,但不是a和b都有
{'r', 'd', 'b', 'm', 'z', 'l'}

>>> a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
{'r', 'd'}

字典

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# 键:值,key: value,键只能是不可变类型
>>> tel = {'jack': 4098, 'sape': 4139}
>>> tel['guido'] = 4127
>>> tel
{'sape': 4139, 'guido': 4127, 'jack': 4098}
>>> tel['jack']
4098
>>> del tel['sape']
>>> tel['irv'] = 4127
>>> tel
{'guido': 4127, 'irv': 4127, 'jack': 4098}
>>> list(tel.keys())
['irv', 'guido', 'jack']
>>> sorted(tel.keys())
['guido', 'irv', 'jack']
>>> 'guido' in tel
True
>>> 'jack' not in tel
False

>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)]) #用dict创建
{'sape': 4139, 'jack': 4098, 'guido': 4127}
>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}
>>> dict(sape=4139, guido=4127, jack=4098) # 键是字符串
{'sape': 4139, 'jack': 4098, 'guido': 4127}

循环技巧

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.items(): # 用items()在字典中循环
... print(k, v)
...
gallahad the pure
robin the brave

>>> for i, v in enumerate(['tic', 'tac', 'toe']):
... print(i, v) # 序列(列表、元组、range)中enumerate可以同时提取索引和值
...
0 tic
1 tac
2 toe

>>> questions = ['name', 'quest', 'favorite color']
>>> answers = ['lancelot', 'the holy grail', 'blue']
>>> for q, a in zip(questions, answers): # 使用zip同时循环多个序列
... 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.

>>> for i in reversed(range(1, 10, 2)): # 使用reversed函数反向取
... print(i)
...
9
7
5
3
1

>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for f in sorted(set(basket)):
... print(f)
...
apple
banana
orange
pear

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

更多的条件控制

1
2
3
4
5
6
7
8
9
10
11
12
# 除了while,if,还可以用:
# is(判断两者是否指向同一个地址,表示的是同一个值),is not
# in(某元素是否存在于一个sequence里面),not in
# > < == != 等等
# x and y:如果x是0,返回0,否则它返回 y 的值。
# x or y:如果x非0,它返回x的值,否则它返回y的值。
# not x:如果x非0,返回False,否则返回True。

>>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
>>> non_null = string1 or string2 or string3
>>> non_null
'Trondheim'

序列间的比较

1
2
3
4
5
6
7
8
9
10
11
12
# 比较的序列类型是同一类型
# 比较的方法是通过逐个元素之间对应比较
# 比较大小规则是按照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)