Martin(Bob大叔)曾在《代码整洁之道》一书打趣地说:当你的代码在作 Code Review 时,审查者要是愤怒地吼道: javascript
“What the fuck is this shit?”
“Dude, What the fuck!” html
等言辞激烈的词语时,那说明你写的代码是 Bad Code,若是审查者只是漫不经心的吐出几个java
“What the fuck?”,python
那说明你写的是 Good Code。衡量代码质量的惟一标准就是每分钟骂出“WTF” 的频率。设计模式
一份优雅、干净、整洁的代码一般自带文档和注释属性,读代码便是读做者的思路。Python 开发中不多要像 Java 同样把遵循某种设计模式做为开发原则来应用到系统中,毕竟设计模式只是一种实现手段而已,代码清晰才是最终目的,而 Python 灵活而不失优雅,这也是为何 Python 可以深受 geek 喜好的缘由之一。app
上周写了一篇:代码这样写更优雅,朋友们纷纷表示但愿再写点儿,今天就接着这个话题写点 Python 中那些 Pythonic 的写法,但愿能够抛砖引玉。python2.7
age = 18
if age > 18 and x < 60:
print("yong man")复制代码
pythonicthis
if 18 < age < 60:
print("yong man")复制代码
理解了链式比较操做,那么你应该知道为何下面这行代码输出的结果是 False。spa
>>> False == False == True
False复制代码
if gender == 'male':
text = '男'
else:
text = '女'复制代码
pythonic.net
text = '男' if gender == 'male' else '女'复制代码
在类C的语言中都支持三目运算 b?x:y,Python之禅有这样一句话:
“There should be one-- and preferably only one --obvious way to do it. ”。
可以用 if/else 清晰表达逻辑时,就不必再额外新增一种方式来实现。
检查某个对象是否为真值时,还显示地与 True 和 False 作比较就显得画蛇添足,不专业
if attr == True:
do_something()
if len(values) != 0: # 判断列表是否为空
do_something()复制代码
pythonic
if attr:
do_something()
if values:
do_something()复制代码
真假值对照表:
类型 | False | True |
---|---|---|
布尔 | False (与0等价) | True (与1等价) |
字符串 | ""( 空字符串) | 非空字符串,例如 " ", "blog" |
数值 | 0, 0.0 | 非0的数值,例如:1, 0.1, -1, 2 |
容器 | [], (), {}, set() | 至少有一个元素的容器对象,例如:[0], (None,), [''] |
None | None | 非None对象 |
for else 是 Python 中特有的语法格式,else 中的代码在 for 循环遍历完全部元素以后执行。
flagfound = False
for i in mylist:
if i == theflag:
flagfound = True
break
process(i)
if not flagfound:
raise ValueError("List argument missing terminal flag.")复制代码
pythonic
for i in mylist:
if i == theflag:
break
process(i)
else:
raise ValueError("List argument missing terminal flag.")复制代码
s1 = "foofish.net"
s2 = "vttalk"
s3 = "welcome to %s and following %s" % (s1, s2)复制代码
pythonic
s3 = "welcome to {blog} and following {wechat}".format(blog="foofish.net", wechat="vttalk")复制代码
很难说用 format 比用 %s 的代码量少,可是 format 更易于理解。
“Explicit is better than implicit --- Zen of Python”
获取列表中的部分元素最早想到的就是用 for 循环根据条件提取元素,这也是其它语言中惯用的手段,而在 Python 中还有强大的切片功能。
items = range(10)
# 奇数
odd_items = []
for i in items:
if i % 2 != 0:
odd_items.append(i)
# 拷贝
copy_items = []
for i in items:
copy_items.append(i)复制代码
pythonic
# 第1到第4个元素的范围区间
sub_items = items[1:4]
# 奇数
odd_items = items[1::2]
#拷贝
copy_items = items[::] 或者 items[:]复制代码
列表元素的下标不只能够用正数表示,仍是用负数表示,最后一个元素的位置是 -1,从右往左,依次递减。
--------------------------
| P | y | t | h | o | n |
--------------------------
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1
--------------------------复制代码
def fib(n):
a, b = 0, 1
result = []
while b < n:
result.append(b)
a, b = b, a+b
return result复制代码
pythonic
def fib(n):
a, b = 0, 1
while a < n:
yield a
a, b = b, a + b复制代码
上面是用生成器生成费波那契数列。生成器的好处就是无需一次性把全部元素加载到内存,只有迭代获取元素时才返回该元素,而列表是预先一次性把所有元素加载到了内存。此外用 yield 代码看起来更清晰。
d = {'name': 'foo'}
if d.has_key('name'):
print(d['name'])
else:
print('unkonw')复制代码
pythonic
d.get("name", "unknow")复制代码
经过 key 分组的时候,不得不每次检查 key 是否已经存在于字典中。
data = [('foo', 10), ('bar', 20), ('foo', 39), ('bar', 49)]
groups = {}
for (key, value) in data:
if key in groups:
groups[key].append(value)
else:
groups[key] = [value]复制代码
pythonic
# 第一种方式
groups = {}
for (key, value) in data:
groups.setdefault(key, []).append(value)
# 第二种方式
from collections import defaultdict
groups = defaultdict(list)
for (key, value) in data:
groups[key].append(value)复制代码
在python2.7以前,构建字典对象通常使用下面这种方式,可读性很是差
numbers = [1,2,3]
my_dict = dict([(number,number*2) for number in numbers])
print(my_dict) # {1: 2, 2: 4, 3: 6}复制代码
pythonic
numbers = [1, 2, 3]
my_dict = {number: number * 2 for number in numbers}
print(my_dict) # {1: 2, 2: 4, 3: 6}
# 还能够指定过滤条件
my_dict = {number: number * 2 for number in numbers if number > 1}
print(my_dict) # {2: 4, 3: 6}复制代码
字典推导式是python2.7新增的特性,可读性加强了不少,相似的仍是列表推导式和集合推导式。
公众号『Python之禅』(id:VTtalk),分享 Python 等技术干货
博客地址:foofish.net/idiomatic_p…