条件语句
- 条件语句的末尾必须加上冒号(:)
Python 不支持 switch 语句,因此,当存在多个条件判断时,我们需要用else if来实现,这在Python中的表达是elif:
1
2
3
4
5
6
7
8
9if x:
statement_1
elif y:
statement_2
...
elif z:
statement_i
else:
statement_n整个条件语句是顺序执行的,如果遇到一个条件满足,在执行完statement后,便会退出整个if、elif、else条件语句,而不会继续向下执行。
循环语句
- 一般通过 for 循环和 while 循环实现
for 循环 Python中的数据结构只要是可迭代的(iterable),比如列表、集合等等,都可以通过下面这种方式遍历
- 遍历列表:
1
2
3
4
5
6
7l = [1, 2, 3, 4]
for item in l:
print(item)
1
2
3
4
- 遍历列表:
字典本身只有键是可迭代的,如果我们要遍历它的值或者是键值对,就需要通过其内置的函数 values() 或者items() 实现。
- 其中,values() 返回字典的值的集合,items()返回键值对的集合
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18d = {'name': 'jason', 'dob': '2000-01-01', 'gender': 'male'}
for k in d: # 遍历字典的键
print(k)
name
dob
gender
for v in d.values(): # 遍历字典的值
print(v)
jason
2000-01-01
male
for k, v in d.items(): # 遍历字典的键值对
print('key: {}, value: {}'.format(k, v))
key: name, value: jason
key: dob, value: 2000-01-01
key: gender, value: male
- 其中,values() 返回字典的值的集合,items()返回键值对的集合
通过集合中的索引来遍历元素: range() 函数
1
2
3
4l = [1, 2, 3, 4, 5, 6, 7]
for index in range(0, len(l)):
if index < 5:
print(l[index])同时需要索引和元素时,用Python内置的函数enumerate 实现:
1
2
3
4l = [1, 2, 3, 4, 5, 6, 7]
for index, item in enumerate(l):
if index < 5:
print(item)在循环语句中,常常搭配 continue和break一起使用。continue,就是让程序跳过当前这层循环,继续执行下面的循环;而break则是指完全跳出所在的整个循环体。在循环中适当加入continue和break,往往能使程序更加简洁、易读。
- e.g. 过多嵌套会使代码冗余
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24# name_price: 产品名称 (str) 到价格 (int) 的映射字典
# name_color: 产品名字 (str) 到颜色 (list of str) 的映射字典
for name, price in name_price.items():
if price < 1000:
if name in name_color:
for color in name_color[name]:
if color != 'red':
print('name: {}, color: {}'.format(name, color))
else:
print('name: {}, color: {}'.format(name, 'None'))
# 加入 continue
# name_price: 产品名称 (str) 到价格 (int) 的映射字典
# name_color: 产品名字 (str) 到颜色 (list of str) 的映射字典
for name, price in name_price.items():
if price >= 1000:
continue
if name not in name_color:
print('name: {}, color: {}'.format(name, 'None'))
continue
for color in name_color[name]:
if color == 'red':
continue
print('name: {}, color: {}'.format(name, color))
- e.g. 过多嵌套会使代码冗余
while 循环
基本同 for 一样
1
2while condition:
....哪个效率高? range() 函数是直接由 C 语言写的,调用它速度非常快
条件与循环的复用
将条件与循环并做一行:
1
expression1 if condition else expression2 for item in iterable
复用用于多个循环。e.g. 给定两个列表x、y,要求返回x、y中所有元素对组成的元祖,相等情况除外
1
[(xx, yy) for xx in x for yy in y if xx != yy]
思考题
1 | attributes = ['name', 'dob', 'gender'] |
answer:1
2
3
4
5
6
7
8
9
10# 一行
[dict(zip(attributes,v)) for v in values]
# 多行
l = []
for value in values:
d = {}
for i in range(3):
d[attributes[i]] = value[i]
l.append(d)