d = {'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
当然可以通过索引来遍历元素
l = [1, 2, 3, 4, 5, 6, 7] for index in range(0, len(l)): if index print(l[index])
1 2 3 4 5
别忘了还有一个更重要的enumerate() 函数
l = [1, 2, 3, 4, 5, 6, 7] for index, item in enumerate(l): if index print(item)
1 2 3 4 5
在循环语句中,要通过continue 或break 一起使用
continue,就是让程序跳过当前这层循环,继续执行下面的循环
break 则是指完全跳出所在的整个循环体
现在找出价格小于1000,颜色不是红色的产品名称和颜色组合,如果不用continue
# name_price: 产品名称 (str) 到价格 (int) 的映射字典 # name_color: 产品名字 (str) 到颜色 (list of str) 的映射字典 for name, price in name_price.items(): if price 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'))
共用了5层for 或if 的嵌套
加上了continue,只有3层
# 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')) for color in name_color[name]: if color == 'red': continue print('name: {}, color: {}'.format(name, color))
while
l = [1, 2, 3, 4] index = 0 while index print(l[index]) index += 1
那么在什么场合使用for和continue
如果只是遍历已知的集合,找出满足条件的元素,使用for更加的简洁
如果需要在满足某个条件前,要不停的重复操作,并且没有特定的集合来遍历
例如
while True: try: text = input('Please enter your questions, enter "q" to exit') if text == 'q': print('Exit system') break ... ... print(response) except as err: print('Encountered error: {}'.format(err)) break
for 循环和while循环的效率问题
i = 0 while i i += 1
for i in range(0, 1000000): pass
range()函数直接时C语言写的,调用的速度非常快,for循环的效率更高
对于有些大神直接写成一行操作
expression1 if condition else expression2 for item in iterable
分解成
for item in iterable: if condition: expression1 else: expression2
如何没有else
expression for item in iterable if condition
现在绘制 y = 2*|x| + 5 的函数图像
只需一行
y = [value * 2 + 5 if x > 0 else -value * 2 + 5 for value in x]