Fork me on GitHub

python3 Pythonic与Python杂记

用字典映射代替switch case语句

1
2
3
4
5
6
7
8
9
switcher ={
0:'sunday',
1:'monday',
2:'thuesday'
}
day = 0
day_name=switcher.get(day,'Unknow')
print(day_name) # sunday
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
def get_sunday():
return 'sunday'
def get_monday():
return 'monday'
def get_thuesday():
return 'thuesday'
def get_default():
return 'Unknow'
switcher ={
0:get_sunday,
1:get_monday,
2:get_thuesday
}
day = 6
day_name=switcher.get(day,get_default)()
print(day_name) # sunday

列表推导式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 列表推到式
# 集合推到式
# map filter
# set
# dict
a = [1,2,3,4,5,6,7,8]
# b = [i*i for i in a]
b = [i**2 for i in a]
print(b) # [1, 4, 9, 16, 25, 36, 49, 64]
c = [i**3 for i in a]
print(c) # [1, 8, 27, 64, 125, 216, 343, 512]
d = [i**3 for i in a if i > 5]
print(d) # [216, 343, 512]
e =(1,2,3,4,5,6,7,8)
f = [i**3 for i in a if i > 5]
print(f) # [216, 343, 512]
g = {i**3 for i in a if i > 5}
print(g) # {216, 512, 343}

字典如何编写列表推导式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
students = {
'喜小乐':18,
'石敢当':20,
'张三':15
}
# 字典
b = {key for key,value in students.items()}
print(b) # {'石敢当', '喜小乐', '张三'}
b = {value for key,value in students.items()}
print(b) # {18, 20, 15}
b = {value:key for key,value in students.items()}
print(b) # {18: '喜小乐', 20: '石敢当', 15: '张三'}
# 元组
b = (key for key,value in students.items())
for x in b:
print(x)
# 喜小乐
# 石敢当
# 张三

None

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# None 空
# 空字符串 空的列表 0 False
a = ''
b = False
c =[]
print(a==None) # False
print(b==None) # False
print(c==None) # False
print(a is None) # False
print(type(None)) # <class 'NoneType'>
a = []
a =''
a = None # 不存在
a = False # 真假
判断为空的方式
if a:
if not a:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Test():
def __len__(self):
return 0
# return 8
# return True
test = Test()
if test:
print('S') # True/8
else:
print('F') # 0
print(len(Test())) # 0
print(bool(Test())) # False
1
2
3
4
5
6
7
8
9
10
11
12
class Test():
def __bool__(self):
return False
def __len__(self):
return True
test = Test()
if test:
print('S')
else:
print('F') # F
-------------本文结束 感谢您的阅读-------------
坚持原创技术分享,您的支持将鼓励我继续创作!