首页后端开发PythonPythonic 的写法让 Python 代码更加简洁

Pythonic 的写法让 Python 代码更加简洁

时间2023-03-24 17:29:17发布访客分类Python浏览1637
导读:背景以前我是写 C++/C# 的,刚开始写 Python 的时候还带着 C# 留下的“口音”,这样一来,代码看起来不仅不正宗,而且不简洁。社区里面把比较正宗的写法称为 “Pythonic ”,直接在解释器上执行 import this 就能...

背景

以前我是写 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 的写法

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.
...
....

最后

都到这里了,是时候图穷匕见了!

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!

pythonimport函数索引异常

若转载请注明出处: Pythonic 的写法让 Python 代码更加简洁
本文地址: https://pptw.com/jishu/234.html
vue权限路由实现方式总结(vue路由实现权限管理) 新技能 | 使用python代码来高效操作Excel表格 (文末赠书5本)

游客 回复需填写必要信息