Python

Python编程惯例

2019-12-07  本文已影响0人  a_code_boy

Python编程惯例

1. 让代码既能当模块被import又能直接执行

if __name__ = '__main__':

2. 用下面的方式判断逻辑 "真"或"假"

if x:
if not x:
name = 'Qiangsheng He'
fruits = ['apple', 'orange']
scores = {'Jim': 88, 'Mary': 78}

# GOOD
if name and fruits and scores:
    print(True)
# NOT SO GOOD
if name != '' and fruits != [] and scores != {}:
    print(True)
True False
非空字符串 空字符串
非0数字 数字0
非空的container:len(x) > 0 空的container:len(x) == 0
- None
布尔True 布尔False
nonzero (2.x) / bool (3.x) nonzero (2.x) / bool (3.x)

3. 善用in运算符

if x in items: # Contains
for x in items: # Iteration

title = 'Python idioms'
# GOOD
if 'd' in title:
    print('Title contains char d')
# NOT SO GOOD
if title.find('d') != -1:
    print('Title not contains char d')

names = ['Jim', 'Mary']
# GOOD
for name in names:
    print(name)
# NOT SO GOOD
i = 0
while i < len(names):
    print(names[i])

4. 不借用临时变量交换值

a, b = 'Jim', 'Mary'

# GOOD
a, b = b, a
# NOT SO GOOD
temp = a
a = b
b = a

5. 用sequence构建字符串

letters = ['J', 'o', 'h', 'n', 's', 'o', 'n']
# GOOD
name = ''.join(letters) # 时间复杂度O(n)
# NOT SO GOOD
name = ''
for letter in letters: # 时间复杂度O(n**2)
    name += letter

6. EAFP is preferable to LBYL

# Python中抛出异常的代价不像其他语言那么大
try: v. if ...: except:

scores = {'Jim': '87'}
# GOOD
try:
    score = int(scores['Jim'])
except (KeyError, TypeError, ValueError):
    score = None
# NOT SO GOOD
if 'Jim' in scores and isinstance(scores['Jim'], str)
    and scores['Jim'].isdigit():
    score = int(scores['Jim'])
else:
    score = None

7. 使用enumerate

names = ['Jim', 'Mary', 'Tom']
# GOOD
for i, name in enumerate(names):
    print(i, name)
# NOT SO GOOD
i = 0
for name in names:
    print(i, name)
    i += 1

8. 用列表推导式式构建lists

nums = list(range(10))
# GOOD
odd_nums = [x for x in nums if x % 2 == 1]
# NOT SO GOOD
odd_nums = []
for num in nums:
    if num % 2 == 1:
        odd_nums.append(num)

9. 通过zip函数组合键和值构建字典

# d = dict(zip(keys, values))

students = ['Jim', 'Mary', 'Tom']
scores = [89, 34, 56]
# GOOD
student_scores = dict(zip(students, scores))
# NOT SO GOOD
student_scores = []
for i, name in enumerate(students):
    student_scores[name] = scores[i]

10. 其他

说明:这篇文章的内容来自于网络,有兴趣的读者可以阅读原文


转载请标明来源

如果文章对你有所把帮助,请动动小手点个赞👍!有任何疑问和建议,可以在下面评论留言。

祝生活愉快!

上一篇 下一篇

猜你喜欢

热点阅读