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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
|
列表
---
语言的内置(built-in)类型。注意与String类比,index也是从0开始, in操作符, 求长度,获得字串,遍历操作类似。
``
[]
[10, 20, 30, 40]
['crunchy frog', 'ram bladder', 'lark vomit']
``
列表中的元素不需要是同一类型的
['spam', 2.0, 5, [10, 20]]
列表[10,20]在另外一个列表中,这叫嵌套列表。
['spam', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]],长度是多少?
列表是 Mutable类型。值可以在原地变。(注意与String的区别)。
IndexError
遍历
for cheese in cheeses:
print(cheese)
for i in range(len(numbers)):
numbers[i] = numbers[i] * 2
for x in []:
print('This never happens.')
讨论软件工程认证数据输入问题。
+操作符用来连接, *操作符用来重复
列表的方法
append
extend
sort
t = ['d', 'c', 'e', 'b', 'a']
t.sort() # 文t.sort()返回什么值?
t
sum - reduce方法,把几个值变成一个值
map方法,把几个值变成另外几个值
def f(x):
return 2*x
list(map(f, [1,2]]))
filter方法,从几个值中选择符合条件的几个值
def f(x):
if x % 2 == 0:
return True
return False
list(filter(f, [1,2,3,4]))
pop
t = ['a', 'b', 'c']
x = t.pop(1) # pop可不带参数,不带参数返回哪个值?
t = ['a', 'b', 'c']
del t[1]
t = ['a', 'b', 'c', 'd', 'e', 'f']
del t[1:5]
t = ['a', 'b', 'c']
t.remove('b')
list_of_characters = list('spam')
list_of_words = 'spam should be filtered'.split()
list_of_words = 'spam-should-be-filtered'.split('-')
join方法
','.join(['1','2','3'])
a = 'banana'
b = 'banana'
a is b # a与b是不是指向同一个值
a == b
a = [1, 2, 3]
b = [1, 2, 3]
a is b # not identical, a and b are not the same object
a == b # equivalent though they have the same values
别名(Aliasing)
a = [1, 2, 3]
b = a
b is a
把变量名与对象联系起来叫做reference。
a与b是指向[1,2,3]的两个references。
因为[1,2,3]是mutable的,所以使用a对[1,2,3]做改变同样影响到b对应的值。
error-prone(易错)
列表作为参数
-----------
def delete_head(t):
del t[0]
letters = ['a', 'b', 'c']
delete_head(letters) # letters and t points to the same list object.
letters
注意区别append与+操作符
---------------------
t1 = [1, 2]
t2 = t1.append(3)
t1
[1, 2, 3]
t2
t3 = t1 + [4]
t3
[1, 2, 3, 4]
t1
[1, 2, 3]
区别如下两个函数
def bad_delete_head(t):
t = t[1:] # WRONG!
def tail(t):
return t[1:]
---------------------------------
字典(Dictionary)
Mutable
超级有用
d = {} or d = dict()
d = {'hot':'热', 'cool':'凉', 'cold':'冷'}
d['warm'] = '温'
d['warm']
d['freezing'] # KeyError
len(d)
'warm' in d
'温' in d.values()
key
value
key-value pair (item)
item的顺序不可预测,不是按照创建时的顺序。
练习:给定一个字符串,数出每个字母出现的频率。
参考
------
- Think Python 2e – Green Tea Press. http://greenteapress.com/thinkpython2/thinkpython2.pdf.
|