• Python代码简洁之道
  • 发布于 2个月前
  • 360 热度
    0 评论
  • 心已凉
  • 8 粉丝 33 篇博客
  •   
背景
以前我是写 C++/C# 的,刚开始写 Python 的时候还带着 C# 留下的“口音”,这样一来,代码看起来不仅不正宗,而且不简洁。社区里面把比较正宗的写法称为 “Pythonic ”,直接在解释器上执行 import this 就能看到 “Pythonic ”的心法,这里就结合我多年的经验总结一下常见的 “Pythonic” 招式。

交换
非 Pythonic 的写法
temp = a 
a = b 
b = temp
Pythonic 的写法
a, b = b ,a
赋值
非 Pythonic 的写法
a = 100
b = 200
Pythonic 的写法
a, b = 100, 200

真假条件
非 Pythonic 的写法
if condition == True:
    pass

if condition == None:
    pass
Pyhonic 的写法
if condition:
    pass

if not condition:
    pass

if condition is None:
    pass
比较链
非 Pythonic 写法
if age > 60 and age < 100:
    print("(60 ~ 100)")
Pythonic 写法
if 60 < age < 100:
    print("(60 ~ 100)")
三元运算
非 Pythonic 写法
if a < b :
    smallest = a
else :
    smallest = b
Pythonic 的写法
smallest = a if a < b else b
列表推导
非 Pythonic 的写法
result = []
for i in range(10):
    result.append(i)
Pythonic 的写法
result = [_ for _ in range(10)]
这个新的形式对于复杂的场景也是支持的,比如下面的例子。
result = []
for i in range(10):
    if i % 2 == 0:
        result.append(i)
可以写成
result = [i for i in range(10) if i % 2 == 0]
字符拼接
非 Pythonic 的写法
chars = ['h', 'e' 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
message = ""
for c in chars:
    message = message + c
print(message)
Pythonic 的写法
chars = ['h', 'e' 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
print(''.join(chars))
字典索引
非 Pythonic 的写法
kv = {
    'hello': 'world'
}

print(kv['hello'])     # 这个时候正常
print(kv['not-exits']) # 这个时候报错
当 key 不存在的情况下,我们去索引它会报异常,字典有一个 get(key, default) 函数可以在 key 不存在的情况下返回默认值。
kv = {
    'hello': 'world'
}

print(kv.get('hello', 'default-str'))     # 打印 world
print(kv.get('not-exits', 'default-str')) # 打印 default-str
资源管理
非 Pythonic 的写法
//堆代码 www.duidaima.com
try:
    f = open("a.txt")
    for line in f:
        print(line)
finally:
    f.close()
Pythonic 的写法
with open("a.txt") as f:
    for line in f:
        print(line)
循环检测
非 Pythonic 的写法
is_break_executed = False
for i in range(5):
    if i == 10:
        is_break_executed = True
        break

if not is_break_executed:
    print("如果没有执行过 break 语句就执行这个流程")
Pythonic 的写法
for i in range(5):
    if i == 10:
        break
else:
    print("如果没有执行过 break 语句就执行这个流程")


import this
打开解释器直接执行 import this 就能看到“The Zen of Python” 了。
Python 3.11.0 (main, Oct 25 2022, 14:13:24) [Clang 14.0.0 (clang-1400.0.29.202)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
...
....

用户评论