条件语句
- 不加 ()
- 结尾加 :
- elif else 和 if 成对使用
- 省略判断条件
- String:空字符串为False,其余为True
- int:0为False,其余为True
- Bool:True为True,False为False
- list/tuple/dict/set:iterable为空解析为False,其余为True
- Object:None解析为False,其余为True
循环语句
- 可迭代的数据结构可通过如下方式遍历
- for item in <iterable>:
- ...
- 字典的遍历
1 d = {'name' : 'jason', 'dob': '2000-01-01', 'gender': 'male' } 2 for k in d: 3 print(k) 4 print(" ") 5 for v in d.values(): 6 print(v) 7 print(" ") 8 for k,v in d.items(): 9 print('key:{}, value:{}'.format(k,v))
- 通过索引遍历
1 # 方法1 2 l = [1,2,3,4,5,6,7] 3 for index in range(0, len(l)): 4 if index < 5: 5 print(l[index]) 6 7 # 方法2 8 l = [1,2,3,4,5,6,7] 9 for index,item in enumerate(l): 10 if index < 5: 11 print(item)
- continue和break
1 #筛选出价格小于1000,且颜色不是红色的所有“产品--颜色”组合 2 # 不使用continue 3 name_price = {'book_1':120,'book_2':500,'book_3':2000,'book_4':200} 4 name_color = {'book_1':['red','blue'],'book_2':['green','blue'],'book_3':['red','blue']} 5 6 for name, price in name_price.items(): 7 if price < 1000: 8 if name in name_color: 9 for color in name_color[name]: 10 if color != 'red': 11 print('name:{},color:{}'.format(name,color)) 12 else: 13 print('name:{},color:{}'.format(name,'None')) 14 15 # 使用continue 16 for name, price in name_price.items(): 17 if price >= 1000: 18 continue 19 if name not in name_color: 20 print('name:{},color:{}'.format(name,'None')) 21 continue 22 for color in name_color[name]: 23 if color == 'red': 24 continue 25 print('name:{},color:{}'.format(name,color))
- 效率
- for:range()是C语言写的,效率较高
- while:i += 1 会设计对象创建和删除(相当于i = new int(i+1))
- 简化写法
1 #按逗号分割单词,去掉首位空字符,过滤掉长度小于等于5的单词,最后返回单词组成的列表 2 text = ' Today, is, Sunday' 3 text_list = [s.strip() for s in text.split(',') if len(s.strip()) >= 5] 4 print(text_list)
1 # 计算函数值y = 2*|x| + 5 2 # expression1 if condition else expression2 for item in iterable 3 # 等价于: 4 # for item in iterable: 5 # if condition: 6 # expression1 7 # else: 8 # expression2 9 x = [-1,0,1,2,3,4] 10 y = [value * 2 + 5 if value > 0 else -value * 2 + 5 for value in x] 11 print(y)