专栏名称: Python之禅
分享Python相关技术干货,偶尔扯扯其它的
目录
相关文章推荐
Python开发者  ·  自己编写作弊软件骗过大厂!00后拿4个顶级o ... ·  2 天前  
Python开发者  ·  突发!OpenAI 紧急上书,呼吁禁用 ... ·  5 天前  
Python开发者  ·  Jupyter Notebook实用插件分享 ·  5 天前  
Python开发者  ·  董事长刺死CTO(2):董事长早就写好复仇名 ... ·  6 天前  
Python中文社区  ·  稳住别慌!用这个量化策略控制回撤,收益逆天! ·  2 天前  
51好读  ›  专栏  ›  Python之禅

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

Python之禅  · 公众号  · Python  · 2017-03-08 18:19

正文

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()

真假值对照表:

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个元素的范围区间






请到「今天看啥」查看全文