一、导言
二、用字典映射代替switch case语句
# 字典代替 switch 语句 # switch () # { # case 0 : # dayName= 'a'; # break; # case 1 : # dayName= 'b'; # break; # case 2 : # dayName= 'c'; # break; # ... # default : # dayName= 'none'; # break; # } def get_a(): return 'a' def get_b(): return 'b' def get_c(): return 'c' def get_default(): return 'none' day=2 switcher = { 0:get_a, 1:get_b, 2:get_c } day_name=switcher.get(day, get_default)() print(day_name) day_name=switcher.get(6, get_default)() print(day_name) 结果: c none
三、列表推导式
# 列表推导式(根据一个列表推到一个新的列表)list set dict 都可以被推导 a = [1,2,3,4,5,6,7,8] b = [i**3 for i in a] print(b) # [1, 8, 27, 64, 125, 216, 343, 512] b = [i**3 for i in a if i>=5] print(b) # [125, 216, 343, 512]
list =[y for x in range(5) for y in range(2)]
print(list) # [0, 1, 0, 1, 0, 1, 0, 1, 0, 1]
a = {1,2,3,4,5,6,7,8} b = {i**3 for i in a} print(b) # {64, 1, 512, 8, 343, 216, 27, 125}
四、字典如何编写列表推导式
students = { '一号':100, '二号':90, '三号':80 } b = [key for key, value in students.items()] print(b) # ['一号', '二号', '三号'] b = {value:key for key, value in students.items()} print(b) # {100: '一号', 90: '二号', 80: '三号'} b = (key for key, value in students.items()) print(b) # <generator object <genexpr> at 0x00000187AB059410> for x in b: print(x) # 一号 # 二号 # 三号
五、 iterator与generator
六、 None
# None 空 不等于 空字符串 空列表 0 False a = '' b = False c = [] print(a==None) print(b==None) print(c==None) print(type(None)) # False # False # False # <class 'NoneType'> 判断空 a=[] /func() / '' if a: if not a:
七、对象存在并不一定是True
None 等于 False
class Test(): def __len__(self): return 0 t = Test() print(bool(t)) # False class Test1(): pass t = Test1() print(bool(t)) # True
八、__len__与__bool__内置方法
class Test(): def __len__(self): return 8 # def __bool__(self): # return 0 print(len(Test())) # 8 print(bool(Test())) # True
class Test(): def __len__(self): print('len func') return 8 def __bool__(self): print('bool func') return False print(bool(Test())) # bool func # False