Q:字典代替switch
A:
#用字典映射,代替switch,枚举回值,举例1
day = 0
switcher = {
0 : 'Sunday',
1 : 'Monday',
2 : 'Tuesday'
}
#表示其它不符合情况,返回Unknown
day_name = switcher.get(day, 'Unkown')
#用字典映射,代替switch,枚举函数,举例2
day = 0
def get_sunday():
return 'Sunday'
def get_monday():
return 'Monday'
def get_tuesday():
return 'Tuesday'
def get_default():
return 'Unkown'
switcher = {
0 : get_sunday,
1 : get_monday,
2 : get_tuesday
}
#表示其它不符合情况,返回get_default函数表示执行函数
day_name = switcher.get(day, get_default)()
Q:列表推导式
A:
注意,集合set{}也可以做列表推导式,dict也可以,元组也可以,更改b的括号即可
列表推导式,举例1
a = [1,2,3,4,5,6,7,8]
#即得到a列表的所有元素遍历,操作
b = [i**2 for i in a]
print(b)
结果
[1,4,9,16,25,36,49,64]
加条件列表推导式,举例2
a = [1,2,3,4,5,6,7,8]
#即得到a列表的所有元素遍历,按条件操作
b = [i**2 for i in a if i>=5]
print(b)
结果
[25,36,49,64]
字典的列表推导式,举例3
students = {
'a': 18,
'b': 20,
'c': 15
}
#只将字典的key提取出来做一个列表
b = [key for key,value in students.items()]
print(b)
输出
[‘a’, ‘b’, ‘c’]
#只将字典的key和value交换做一个列表
b = [value:key for key,value in students.items()]
print(b)
输出
[18: ‘a’, 20: ‘b’, 15: ‘c’]
#只将字典的key提取出来做一个元组,不推荐
b = (value:key for key,value in students.items())
for x in b:
print(x)
输出
a
b
c
Q:None需要注意的问题
A:
类型和值上None都不等于空字符串’’,空列表[],0,False
类型是:NoneType
not a和a is None不同
not a时’’ [] False,None都可以得到True的结果,尽量选择not a
a is None只有None可以得到True的结果