本系列为《编写高质量代码-改善Python程序的91个建议》的读书笔记。
温馨提醒:在阅读本书之前,强烈建议先仔细阅读:PEP规范,增强代码的可阅读性,配合优雅的pycharm编辑器(开启pep8
检查)写出规范代码,是Python
入门的第一步。
本书主要内容
1)容易被忽视的重要概念和常识,如代码的布局和编写函数的原则等;
2)编写Python
程序管用的方法,如利用assert
语句去发现问题,使用enumerate()
获取序列迭代的索引和值等;
3)语法中的关键条款,如有节制地使用from…import
语句,异常处理的几点基本原则等;
4)常见库的使用,如按需选择sort()
或者sorted()
,使用Queue
使多线程更安全等;
5)Python
设计模式的使用,如用发布订阅模式实现松耦合,用状态模式美化代码等;
6)Python
内部机制,如名字查找机制,描述符机制等;
7)开发工具的使用,如pip
等各种开发工具的使用,各种代码测试用具的使用等;
8)Python
代码的性能分析,优化的原则,工具,技巧,以及常见性能问题的解决等。
建议1:理解Pythonic概念
1)Pythonic
的定义:充分体现Python
自身特色的代码风格。
The Zen of Python
(Python
之禅)
>>> 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.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
>>>
- 快速排序
def sort_quick(array):
"""
快速排序
:param array:
:return:
"""
less = list()
greater = list()
if len(array) <= 1:
return array
pivot = array.pop()
for index, item in enumerate(array):
if item <= pivot:
less.append(item)
else:
greater.append(item)
return sort_quick(less) + [pivot] + sort_quick