CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!
CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!
Path: blob/master/番外篇/Python编程惯例.md
Views: 729
Python编程惯例
“惯例”这个词指的是“习惯的做法,常规的办法,一贯的做法”,与这个词对应的英文单词叫“idiom”。由于Python跟其他很多编程语言在语法和使用上还是有比较显著的差别,因此作为一个Python开发者如果不能掌握这些惯例,就无法写出“Pythonic”的代码。下面我们总结了一些在Python开发中的惯用的代码。
让代码既可以被导入又可以被执行。
用下面的方式判断逻辑“真”或“假”。
好的代码:
不好的代码:
善于使用in运算符。
好的代码:
不好的代码:
不使用临时变量交换两个值。
用序列构建字符串。
好的代码:
不好的代码:
EAFP优于LBYL。
EAFP - Easier to Ask Forgiveness than Permission.
LBYL - Look Before You Leap.
好的代码:
不好的代码:
使用enumerate进行迭代。
好的代码:
不好的代码:
用生成式生成列表。
好的代码:
不好的代码:
用zip组合键和值来创建字典。
好的代码:
不好的代码:
说明:这篇文章的内容来自于网络,有兴趣的读者可以阅读原文。