代碼這樣寫(xiě)不止于優(yōu)雅(Python版)

Martin(Bob大叔)曾在《代碼整潔之道》一書(shū)打趣地說(shuō):當(dāng)你的代碼在做 Code Review 時(shí),審查者要是憤怒地吼道:

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

等言辭激烈的詞語(yǔ)時(shí),那說(shuō)明你寫(xiě)的代碼是 Bad Code,如果審查者只是漫不經(jīng)心的吐出幾個(gè)

“What the fuck?”,

那說(shuō)明你寫(xiě)的是 Good Code。衡量代碼質(zhì)量的唯一標(biāo)準(zhǔn)就是每分鐘罵出“WTF” 的頻率。

一份優(yōu)雅、干凈、整潔的代碼通常自帶文檔和注釋屬性,讀代碼即是讀作者的思路。Python 開(kāi)發(fā)中很少要像 Java 一樣把遵循某種設(shè)計(jì)模式作為開(kāi)發(fā)原則來(lái)應(yīng)用到系統(tǒng)中,畢竟設(shè)計(jì)模式只是一種實(shí)現(xiàn)手段而已,代碼清晰才是最終目的,而 Python 靈活而不失優(yōu)雅,這也是為什么 Python 能夠深受 geek 喜愛(ài)的原因之一。

上周寫(xiě)了一篇:代碼這樣寫(xiě)更優(yōu)雅,朋友們紛紛表示希望再寫(xiě)點(diǎn)兒,今天就接著這個(gè)話題寫(xiě)點(diǎn) Python 中那些 Pythonic 的寫(xiě)法,希望可以拋磚引玉。

1、鏈?zhǔn)奖容^操作

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

pythonic

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

理解了鏈?zhǔn)奖容^操作,那么你應(yīng)該知道為什么下面這行代碼輸出的結(jié)果是 False。

>>> False == False == True 
False

2、if/else 三目運(yùn)算

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

pythonic

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

在類C的語(yǔ)言中都支持三目運(yùn)算 b?x:y,Python之禪有這樣一句話:

“There should be one-- and preferably only one --obvious way to do it. ”。

能夠用 if/else 清晰表達(dá)邏輯時(shí),就沒(méi)必要再額外新增一種方式來(lái)實(shí)現(xiàn)。

3、真值判斷

檢查某個(gè)對(duì)象是否為真值時(shí),還顯示地與 True 和 False 做比較就顯得多此一舉,不專業(yè)

if attr == True:
    do_something()

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

pythonic

if attr:
    do_something()

if values:
    do_something()

真假值對(duì)照表:

類型 False True
布爾 False (與0等價(jià)) True (與1等價(jià))
字符串 ""( 空字符串) 非空字符串,例如 " ", "blog"
數(shù)值 0, 0.0 非0的數(shù)值,例如:1, 0.1, -1, 2
容器 [], (), {}, set() 至少有一個(gè)元素的容器對(duì)象,例如:[0], (None,), ['']
None None 非None對(duì)象

4、for/else語(yǔ)句

for else 是 Python 中特有的語(yǔ)法格式,else 中的代碼在 for 循環(huán)遍歷完所有元素之后執(zhí)行。

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

很難說(shuō)用 format 比用 %s 的代碼量少,但是 format 更易于理解。

“Explicit is better than implicit --- Zen of Python”

6、列表切片

獲取列表中的部分元素最先想到的就是用 for 循環(huán)根據(jù)條件提取元素,這也是其它語(yǔ)言中慣用的手段,而在 Python 中還有強(qiáng)大的切片功能。

items = range(10)

# 奇數(shù)
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個(gè)元素的范圍區(qū)間
sub_items = items[1:4]
# 奇數(shù)
odd_items = items[1::2]
#拷貝
copy_items = items[::] 或者 items[:]

列表元素的下標(biāo)不僅可以用正數(shù)表示,還是用負(fù)數(shù)表示,最后一個(gè)元素的位置是 -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

上面是用生成器生成費(fèi)波那契數(shù)列。生成器的好處就是無(wú)需一次性把所有元素加載到內(nèi)存,只有迭代獲取元素時(shí)才返回該元素,而列表是預(yù)先一次性把全部元素加載到了內(nèi)存。此外用 yield 代碼看起來(lái)更清晰。

8、獲取字典元素

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

pythonic

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

9、預(yù)設(shè)字典默認(rèn)值

通過(guò) key 分組的時(shí)候,不得不每次檢查 key 是否已經(jīng)存在于字典中。

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、字典推導(dǎo)式

在python2.7之前,構(gòu)建字典對(duì)象一般使用下面這種方式,可讀性非常差

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}

# 還可以指定過(guò)濾條件
my_dict = {number: number * 2 for number in numbers if number > 1}
print(my_dict)  # {2: 4, 3: 6}

字典推導(dǎo)式是python2.7新增的特性,可讀性增強(qiáng)了很多,類似的還是列表推導(dǎo)式和集合推導(dǎo)式。

原文:https://foofish.net/idiomatic_part2.html

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容