您的位置:首页 > 编程语言 > Python开发

代码这样写不止于优雅(Python版)

2017-09-26 13:14 465 查看
Martin(Bob大叔)曾在《代码整洁之道》一书打趣地说:当你的代码在做 Code Review 时,审查者要是愤怒地吼道:

“What the fuck is this shit?”
“Dude, What the fuck!”

等言辞激烈的词语时,那说明你写的代码是 Bad Code,如果审查者只是漫不经心的吐出几个

“What the fuck?”,

那说明你写的是 Good Code。衡量代码质量的唯一标准就是每分钟骂出“WTF” 的频率。



一份优雅、干净、整洁的代码通常自带文档和注释属性,读代码即是读作者的思路。Python 开发中很少要像 Java 一样把遵循某种设计模式作为开发原则来应用到系统中,毕竟设计模式只是一种实现手段而已,代码清晰才是最终目的,而 Python 灵活而不失优雅,这也是为什么 Python 能够深受 geek 喜爱的原因之一。

上周写了一篇:代码这样写更优雅,朋友们纷纷表示希望再写点儿,今天就接着这个话题写点 Python 中那些 Pythonic 的写法,希望可以抛砖引玉。

1、链式比较操作

age = 18
if age > 18 and x < 60:
print("yong man")

pythonic

if 18 < age < 60:
print("yong man")

理解了链式比较操作,那么你应该知道为什么下面这行代码输出的结果是 False。

>>> False == False == True
False

2、if/else 三目运算

if gender == 'male':
text = '男'
else:
text = '女'

pythonic

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 清晰表达逻辑时,就没必要再额外新增一种方式来实现。

3、真值判断

检查某个对象是否为真值时,还显示地与 True 和 False 做比较就显得多此一举,不专业

if attr == True:
do_something()

if len(values) != 0: # 判断列表是否为空
do_something()

pythonic

if attr:
do_something()

if values:
do_something()

真假值对照表:

类型FalseTrue
布尔False (与0等价)True (与1等价)
字符串""( 空字符串)非空字符串,例如 " ", "blog"
数值0, 0.0非0的数值,例如:1, 0.1, -1, 2
容器[], (), {}, set()至少有一个元素的容器对象,例如:[0], (None,), ['']
NoneNone非None对象

4、for/else语句

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

5、字符串格式化

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”

6、列表切片

获取列表中的部分元素最先想到的就是用 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
--------------------------

7、善用生成器

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 代码看起来更清晰。

8、获取字典元素

d = {'name': 'foo'}
if d.has_key('name'):
print(d['name'])
else:
print('unkonw')

pythonic

d.get("name", "unknow")

9、预设字典默认值

通过 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)

10、字典推导式

在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新增的特性,可读性增强了很多,类似的还是列表推导式和集合推导式。

原文:https://foofish.net/idiomatic_part2.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: