python Standard

python开发中常用代码

1、让代码既可以被导入又可以被执行

1
if __name__ == '__main__':

2、逻辑判断

1
2
3
4
5
name = 'jelly'
fruits = ['apple','orange','grape']
owners = {'101':'应敏婕','102':'罗一芳'}
if name and fruits and owners:
print('应敏婕 love friuts 罗一芳')

3、善用in

1
2
if 'I' in name:
print('this is a l in it!')

4、不使用临时变量替换两个值

1
a,b=b,a

5、EAFP优于LBYL。

1
2
3
EAFP - Easier to Ask Forgiveness than Permission.

LBYL - Look Before You Leap.
1
2
3
4
5
6
7
8
#好的代码:

d = {'x': '5'}
try:
value = int(d['x'])
print(value)
except (KeyError, TypeError, ValueError):
value = None

6、使用enumerate进行迭代

1
2
3
fruits = ['orange', 'grape', 'pitaya', 'blueberry']
for index, fruit in enumerate(fruits):
print(index, ':', fruit)

7、善用生成式

1
2
3
data=[1,2,3]
result = [num*3 for num in data if num>1]
print(result) #[4,6]

8、zip组合键和值创建字典

1
2
3
4
key = ['101,'102','103']
values = ['应敏婕','jelly','罗一芳']
d = dict(zip(keys,values))
print(d)