符合语言习惯的 Python 优雅编程技巧

简介:

Python最大的优点之一就是语法简洁,好的代码就像伪代码一样,干净、整洁、一目了然。要写出 Pythonic(优雅的、地道的、整洁的)代码,需要多看多学大牛们写的代码,github 上有很多非常优秀的源代码值得阅读,比如:requests、flask、tornado,下面列举一些常见的Pythonic写法。

0. 程序必须先让人读懂,然后才能让计算机执行。

“Programs must be written for people to read, and only incidentally for machines to execute.”

1. 交换赋值

##不推荐
temp = a
a = b
b = a

##推荐
a, b = b, a # 先生成一个元组(tuple)对象,然后unpack

2. Unpacking

##不推荐
l = ['David', 'Pythonista', '+1-514-555-1234']
first_name = l[0]
last_name = l[1]
phone_number = l[2]

##推荐
l = ['David', 'Pythonista', '+1-514-555-1234']
first_name, last_name, phone_number = l
# Python 3 Only
first, *middle, last = another_list

3. 使用操作符in

##不推荐
if fruit == "apple" or fruit == "orange" or fruit == "berry":
# 多次判断

##推荐
if fruit in ["apple", "orange", "berry"]:
# 使用 in 更加简洁

4. 字符串操作

##不推荐
colors = ['red', 'blue', 'green', 'yellow']

result = ''
for s in colors:
result += s # 每次赋值都丢弃以前的字符串对象, 生成一个新对象

##推荐
colors = ['red', 'blue', 'green', 'yellow']
result = ''.join(colors) # 没有额外的内存分配

5. 字典键值列表

##不推荐
for key in my_dict.keys():
# my_dict[key] ...

##推荐
for key in my_dict:
# my_dict[key] ...

# 只有当循环中需要更改key值的情况下,我们需要使用 my_dict.keys()
# 生成静态的键值列表。

6. 字典键值判断

##不推荐
if my_dict.has_key(key):
# ...do something with d[key]

##推荐
if key in my_dict:
# ...do something with d[key]

7. 字典 get 和 setdefault 方法

##不推荐
navs = {}
for (portfolio, equity, position) in data:
if portfolio not in navs:
navs[portfolio] = 0
navs[portfolio] += position * prices[equity]
##推荐
navs = {}
for (portfolio, equity, position) in data:
# 使用 get 方法
navs[portfolio] = navs.get(portfolio, 0) + position * prices[equity]
# 或者使用 setdefault 方法
navs.setdefault(portfolio, 0)
navs[portfolio] += position * prices[equity]

8. 判断真伪

##不推荐
if x == True:
# ....
if len(items) != 0:
# ...
if items != []:
# ...

##推荐
if x:
# ....
if items:
# ...

9. 遍历列表以及索引

##不推荐
items = 'zero one two three'.split()
# method 1
i = 0
for item in items:
print i, item
i += 1
# method 2
for i in range(len(items)):
print i, items[i]

##推荐
items = 'zero one two three'.split()
for i, item in enumerate(items):
print i, item

10. 列表推导

##不推荐
new_list = []
for item in a_list:
if condition(item):
new_list.append(fn(item))

##推荐
new_list = [fn(item) for item in a_list if condition(item)]

11. 列表推导-嵌套

##不推荐
for sub_list in nested_list:
if list_condition(sub_list):
for item in sub_list:
if item_condition(item):
# do something...
##推荐
gen = (item for sl in nested_list if list_condition(sl) \
for item in sl if item_condition(item))
for item in gen:
# do something...

12. 循环嵌套

##不推荐
for x in x_list:
for y in y_list:
for z in z_list:
# do something for x & y

##推荐
from itertools import product
for x, y, z in product(x_list, y_list, z_list):
# do something for x, y, z

13. 尽量使用生成器代替列表

##不推荐
def my_range(n):
i = 0
result = []
while i < n:
result.append(fn(i))
i += 1
return result # 返回列表

##推荐
def my_range(n):
i = 0
result = []
while i < n:
yield fn(i) # 使用生成器代替列表
i += 1
*尽量用生成器代替列表,除非必须用到列表特有的函数。

14. 中间结果尽量使用imap/ifilter代替map/filter

##不推荐
reduce(rf, filter(ff, map(mf, a_list)))

##推荐
from itertools import ifilter, imap
reduce(rf, ifilter(ff, imap(mf, a_list)))
*lazy evaluation 会带来更高的内存使用效率,特别是当处理大数据操作的时候。

15. 使用any/all函数

##不推荐
found = False
for item in a_list:
if condition(item):
found = True
break
if found:
# do something if found...

##推荐
if any(condition(item) for item in a_list):
# do something if found...

16. 属性(property)

##不推荐
class Clock(object):
def __init__(self):
self.__hour = 1
def setHour(self, hour):
if 25 > hour > 0: self.__hour = hour
else: raise BadHourException
def getHour(self):
return self.__hour

##推荐
class Clock(object):
def __init__(self):
self.__hour = 1
def __setHour(self, hour):
if 25 > hour > 0: self.__hour = hour
else: raise BadHourException
def __getHour(self):
return self.__hour
hour = property(__getHour, __setHour)

17. 使用 with 处理文件打开

##不推荐
f = open("some_file.txt")
try:
data = f.read()
# 其他文件操作..
finally:
f.close()

##推荐
with open("some_file.txt") as f:
data = f.read()
# 其他文件操作...

18. 使用 with 忽视异常(仅限Python 3)

##不推荐
try:
os.remove("somefile.txt")
except OSError:
pass

##推荐
from contextlib import ignored # Python 3 only

with ignored(OSError):
os.remove("somefile.txt")

19. 使用 with 处理加锁

##不推荐
import threading
lock = threading.Lock()

lock.acquire()
try:
# 互斥操作...
finally:
lock.release()

##推荐
import threading
lock = threading.Lock()

with lock:
# 互斥操作...

20. 参考

1) Idiomatic Python:

http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html

2) PEP 8: Style Guide for Python Code:

http://www.python.org/dev/peps/pep-0008/


原文发布时间为:2018-11-15
本文作者:安生
本文来自云栖社区合作伙伴“ 数据与算法之美”,了解相关信息可以关注“ 数据与算法之美”。
相关文章
|
7月前
|
存储 JavaScript Java
(Python基础)新时代语言!一起学习Python吧!(四):dict字典和set类型;切片类型、列表生成式;map和reduce迭代器;filter过滤函数、sorted排序函数;lambda函数
dict字典 Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。 我们可以通过声明JS对象一样的方式声明dict
435 2
|
7月前
|
算法 Java Docker
(Python基础)新时代语言!一起学习Python吧!(三):IF条件判断和match匹配;Python中的循环:for...in、while循环;循环操作关键字;Python函数使用方法
IF 条件判断 使用if语句,对条件进行判断 true则执行代码块缩进语句 false则不执行代码块缩进语句,如果有else 或 elif 则进入相应的规则中执行
1247 1
|
8月前
|
数据采集 机器学习/深度学习 人工智能
Python:现代编程的首选语言
Python:现代编程的首选语言
1280 102
|
8月前
|
数据采集 机器学习/深度学习 算法框架/工具
Python:现代编程的瑞士军刀
Python:现代编程的瑞士军刀
461 104
|
8月前
|
人工智能 自然语言处理 算法框架/工具
Python:现代编程的首选语言
Python:现代编程的首选语言
356 103
|
8月前
|
机器学习/深度学习 人工智能 数据挖掘
Python:现代编程的首选语言
Python:现代编程的首选语言
370 82
|
7月前
|
Python
Python编程:运算符详解
本文全面详解Python各类运算符,涵盖算术、比较、逻辑、赋值、位、身份、成员运算符及优先级规则,结合实例代码与运行结果,助你深入掌握Python运算符的使用方法与应用场景。
465 3
|
7月前
|
数据处理 Python
Python编程:类型转换与输入输出
本教程介绍Python中输入输出与类型转换的基础知识,涵盖input()和print()的使用,int()、float()等类型转换方法,并通过综合示例演示数据处理、错误处理及格式化输出,助你掌握核心编程技能。
686 3
|
7月前
|
并行计算 安全 计算机视觉
Python多进程编程:用multiprocessing突破GIL限制
Python中GIL限制多线程性能,尤其在CPU密集型任务中。`multiprocessing`模块通过创建独立进程,绕过GIL,实现真正的并行计算。它支持进程池、队列、管道、共享内存和同步机制,适用于科学计算、图像处理等场景。相比多线程,多进程更适合利用多核优势,虽有较高内存开销,但能显著提升性能。合理使用进程池与通信机制,可最大化效率。
486 3
|
7月前
|
存储 Java 索引
(Python基础)新时代语言!一起学习Python吧!(二):字符编码由来;Python字符串、字符串格式化;list集合和tuple元组区别
字符编码 我们要清楚,计算机最开始的表达都是由二进制而来 我们要想通过二进制来表示我们熟知的字符看看以下的变化 例如: 1 的二进制编码为 0000 0001 我们通过A这个字符,让其在计算机内部存储(现如今,A 字符在地址通常表示为65) 现在拿A举例: 在计算机内部 A字符,它本身表示为 65这个数,在计算机底层会转为二进制码 也意味着A字符在底层表示为 1000001 通过这样的字符表示进行转换,逐步发展为拥有127个字符的编码存储到计算机中,这个编码表也被称为ASCII编码。 但随时代变迁,ASCII编码逐渐暴露短板,全球有上百种语言,光是ASCII编码并不能够满足需求
320 4

推荐镜像

更多