Pythonic
我们将非常Python
的Python
的代码风格称为Pythonic。也就是说,Pythonic是使用Python
写出简洁优美代码的风格:
交换多个数字
a = 0
b = 0
a, b = b, a
生成列表
[i**2 for i in range(0, 41) if i % 2 == 0]
检查列表是否为空
if not lists:
print('lists is empty')
打开文件或数据处理
with open(r 'C:\usr\admin\documents\data.txt') as afile:
for line in afile:
pass
返回数据
return [a, b], a, b
"""
In fact, it returns tuple ([a, b], a, b)
"""
以上例子,都是可以通过Not Pythonic的方式实现,然而,使用Pythonic不仅可以让代码更加简洁,还可以增加代码的“可读性”。