python-编码惯例
python-编码惯例
(1)只有模块作为脚本运行时才执行其中的代码
if __name__ == '__main__': print('main') #do something
(2)判断逻辑真和逻辑假
if x: #do something if not x: #do something
好的代码
name = 'Safe' pets = ['Dog', 'Cat', 'Hamster'] owners = {'Safe': 'Cat', 'Tom': 'Dog'} if name and pets and owners: print('We have pets.')
不好的代码
name = 'Safe' pets = ['Dog', 'Cat', 'Hamster'] owners = {'Safe': 'Cat', 'Tom': 'Dog'} if name != '' and len(pets) > 0 and owners != {}: print('We have pets.')
(3)善于使用in操作符
if x in items: #do something for x in items: #do something
好的代码
name = 'Safe Hammad' if 'H' in name: print('This name has H in it.') pets = ['Dog', 'Cat', 'Hamster'] for pet in pets: print('A', pet, 'can be very cute!')
不好的代码
name = 'Safe Hammad' if name.find('H') != -1: print('This name has H in it.') pets = ['Dog', 'Cat', 'Hamster'] i = 0 while i < len(pets): print('A', pets[i], 'can be very cute!') i += 1
(4)不使用临时变量交互两个变量的值
好的代码
a, b = 1, 2 print(a, b) #1 2 a, b = b, a print(a, b) #2 1
不好的代码
a, b = 1, 2 print(a, b) #1 2 temp = a a = b b = temp print(a, b) #2 1
(5)用序列构建字符串
好的代码
eles = ['a', 'b', 'c', 'd', 'e'] name = ''.join(eles) print(name) #abcde
不好的代码
eles = ['a', 'b', 'c', 'd', 'e'] name = '' for ele in eles: name += ele print(name) #abcde
(6)EAFP优于LBYL
EAFP - Easier to Ask Forgiveness than Permission.
LBYL - Look Before You Leap.
好的代码
d = {'x': '5'} try: value = int(d['x']) except (KeyError, TypeError, ValueError): value = None
不好的代码
d = {'x': '5'} if 'x' in d and \ isinstance(d['x'], str) and \ d['x'].isdigit(): value = int(d['x']) else: value = None
(7)使用enumerate进行迭代
好的代码
names = ['tom', 'lily', 'marton'] for i, name in enumerate(names): print(i, name) #0 tom #1 lily #2 marton
不好的代码
names = ['tom', 'lily', 'marton'] i = 0 for name in names: print(i, name) i += 1 #0 tom #1 lily #2 marton
(8)用解析式生成列表
好的代码
data = [1, 5, 9, 10, 20, 8] res = [i for i in data if i % 2 == 0] print(res) #[10, 20, 8]
不好的代码
data = [1, 5, 9, 10, 20, 8] res = [] for i in data: if i % 2 == 0: res.append(i) print(res) #[10, 20, 8]
(9)用zip组合键和值来创建字典
好的代码
nums = ['101', '102'] names = ['tom', 'lily'] d = dict(zip(nums, names)) print(d) #{'101': 'tom', '102': 'lily'}
不好的代码
nums = ['101', '102'] names = ['tom', 'lily'] d = {} for i, k in enumerate(nums): d[k] = names[i] print(d) #{'101': 'tom', '102': 'lily'}
参考资料:python惯例
参考资料:python idioms