Python惯例的代码有哪些-创新互联

这篇文章主要讲解了“Python惯例的代码有哪些”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Python惯例的代码有哪些”吧!

创新互联-专业网站定制、快速模板网站建设、高性价比宝清网站开发、企业建站全套包干低至880元,成熟完善的模板库,直接使用。一站式宝清网站制作公司更省心,省钱,快速模板网站建设找我们,业务覆盖宝清地区。费用合理售后完善,10年实体公司更值得信赖。

一 . 让代码既可以被导入又可以被执行。

if __name__ == '__main__':

二 . 用下面的方式判断逻辑“真”或“假”。

if x:
if not x:

好的代码:

name = 'jackfrued'
fruits = ['apple', 'orange', 'grape']
owners = {'1001': '骆昊', '1002': '王大锤'}
if name and fruits and owners:
 print('I love fruits!')

不好的代码:

name = 'jackfrued'
fruits = ['apple', 'orange', 'grape']
owners = {'1001': '骆昊', '1002': '王大锤'}
if name != '' and len(fruits) > 0 and owners != {}:
 print('I love fruits!')

三 . 善于使用in运算符。

if x in items: # 包含
for x in items: # 迭代

好的代码:

name = 'Hao LUO'
if 'L' in name:
 print('The name has an L in it.')

不好的代码:

name = 'Hao LUO'
if name.find('L') != -1:
 print('This name has an L in it!')

四 . 不使用临时变量交换两个值。

a, b = b, a

五 . 用序列构建字符串。

好的代码:

chars = ['j', 'a', 'c', 'k', 'f', 'r', 'u', 'e', 'd']
name = ''.join(chars)
print(name) # jackfrued

不好的代码:

chars = ['j', 'a', 'c', 'k', 'f', 'r', 'u', 'e', 'd']
name = ''
for char in chars:
 name += char
print(name) # jackfrued

六 . EAFP优于LBYL。

EAFP - Easier to Ask Forgiveness than Permission.

LBYL - Look Before You Leap.

好的代码:

d = {'x': '5'}
try:
 value = int(d['x'])
 print(value)
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'])
 print(value)
else:
 value = None

七 . 使用enumerate进行迭代。

好的代码:

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

不好的代码:

fruits = ['orange', 'grape', 'pitaya', 'blueberry']
index = 0
for fruit in fruits:
 print(index, ':', fruit)
 index += 1

八 . 用生成式生成列表。

好的代码:

data = [7, 20, 3, 15, 11]
result = [num * 3 for num in data if num > 10]
print(result) # [60, 45, 33]

不好的代码:

data = [7, 20, 3, 15, 11]
result = []
for i in data:
 if i > 10:
 result.append(i * 3)
print(result) # [60, 45, 33]

九 . 用zip组合键和值来创建字典。

好的代码:

keys = ['1001', '1002', '1003']
values = ['骆昊', '王大锤', '白元芳']
d = dict(zip(keys, values))
print(d)

不好的代码:

keys = ['1001', '1002', '1003']
values = ['骆昊', '王大锤', '白元芳']
d = {}
for i, key in enumerate(keys):
 d[key] = values[i]
print(d)

感谢各位的阅读,以上就是“Python惯例的代码有哪些”的内容了,经过本文的学习后,相信大家对Python惯例的代码有哪些这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是创新互联,小编将为大家推送更多相关知识点的文章,欢迎关注!


网页名称:Python惯例的代码有哪些-创新互联
标题路径:http://scyanting.com/article/coesdj.html