值得收藏!15個 Pythonic 的程式碼範例

2020-10-10 13:00:40

Python由於語言的簡潔性,讓我們以人類思考的方式來寫程式碼,新手更容易上手,老鳥更愛不釋手。

要寫出 Pythonic(優雅的、地道的、整潔的)程式碼,還要平時多觀察那些大牛程式碼,Github 上有很多非常優秀的原始碼值得閱讀,比如:requests、flask、tornado,這裡小明收集了一些常見的 Pythonic 寫法,幫助你養成寫優秀程式碼的習慣。

01. 變數交換

Bad

tmp = a
a = b
b = tmp

Pythonic

a,b = b,a

02. 列表推導

Bad

my_list = []
for i in range(10):
    my_list.append(i*2)

Pythonic

my_list = [i*2 for i in range(10)]

03. 單行表示式

雖然列表推導式由於其簡潔性及表達性,被廣受推崇。

但是有許多可以寫成單行的表示式,並不是好的做法。

Bad

print 'one'; print 'two'

if x == 1: print 'one'

if <complex comparison> and <other complex comparison>:
    # do something

Pythonic

print 'one'
print 'two'

if x == 1:
    print 'one'

cond1 = <complex comparison>
cond2 = <other complex comparison>
if cond1 and cond2:
    # do something

04. 帶索引遍歷

Bad

for i in range(len(my_list)):
    print(i, "-->", my_list[i])

Pythonic

for i,item in enumerate(my_list):
    print(i, "-->",item)

05. 序列解包

Pythonic

a, *rest = [1, 2, 3]
# a = 1, rest = [2, 3]

a, *middle, c = [1, 2, 3, 4]
# a = 1, middle = [2, 3], c = 4

06. 字串拼接

Bad

letters = ['s', 'p', 'a', 'm']
s=""
for let in letters:
    s += let

Pythonic

letters = ['s', 'p', 'a', 'm']
word = ''.join(letters)

07. 真假判斷

Bad

if attr == True:
    print 'True!'

if attr == None:
    print 'attr is None!'

Pythonic

if attr:
    print 'attr is truthy!'

if not attr:
    print 'attr is falsey!'

if attr is None:
    print 'attr is None!'

08. 存取字典元素

Bad

d = {'hello': 'world'}
if d.has_key('hello'):
    print d['hello']    # prints 'world'
else:
    print 'default_value'

Pythonic

d = {'hello': 'world'}

print d.get('hello', 'default_value') # prints 'world'
print d.get('thingy', 'default_value') # prints 'default_value'

# Or:
if 'hello' in d:
    print d['hello']

09. 操作列表

Bad

a = [3, 4, 5]
b = []
for i in a:
    if i > 4:
        b.append(i)

Pythonic

a = [3, 4, 5]
b = [i for i in a if i > 4]
# Or:
b = filter(lambda x: x > 4, a)

Bad

a = [3, 4, 5]
for i in range(len(a)):
    a[i] += 3

Pythonic

a = [3, 4, 5]
a = [i + 3 for i in a]
# Or:
a = map(lambda i: i + 3, a)

10. 檔案讀取

Bad

f = open('file.txt')
a = f.read()
print a
f.close()

Pythonic

with open('file.txt') as f:
    for line in f:
        print line

11. 程式碼續行

Bad

my_very_big_string = """For a long time I used to go to bed early. Sometimes, \
    when I had put out my candle, my eyes would close so quickly that I had not even \
    time to say 「I’m going to sleep.」"""

from some.deep.module.inside.a.module import a_nice_function, another_nice_function, \
    yet_another_nice_function

Pythonic

my_very_big_string = (
    "For a long time I used to go to bed early. Sometimes, "
    "when I had put out my candle, my eyes would close so quickly "
    "that I had not even time to say 「I’m going to sleep.」"
)

from some.deep.module.inside.a.module import (
    a_nice_function, another_nice_function, yet_another_nice_function)

12. 顯式程式碼

Bad

def make_complex(*args):
    x, y = args
    return dict(**locals())

Pythonic

def make_complex(x, y):
    return {'x': x, 'y': y}

13. 使用預留位置

Pythonic

filename = 'foobar.txt'
basename, _, ext = filename.rpartition('.')

14. 鏈式比較

Bad

if age > 18 and age < 60:
    print("young man")

Pythonic

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

理解了鏈式比較操作,那麼你應該知道為什麼下面這行程式碼輸出的結果是 False

>>> False == False == True 
False

15. 三目運算

這個保留意見。隨使用習慣就好。

Bad

if a > 2:
    b = 2
else:
    b = 1
#b = 2

Pythonic

a = 3   

b = 2 if a > 2 else 1
#b = 2

參考檔案

文末福利

本人原創的 《PyCharm 中文指南》一書前段時間一經發布,就火爆了整個 Python 圈,釋出僅一天的時間,下載量就突破了 1000 ,並且在當天就在 Github 上就收穫了數百的 star,截至目前,下載量已經破萬。

這本書一共將近 200 頁內含大量的圖解製作之精良,值得每個 Python 工程師 人手一份。

為方便你下載,我將這本書上傳到 百度網路硬碟上了,你可以自行獲取。

連結:https://pan.baidu.com/s/1-NzATHFtaTV1MQzek70iUQ

密碼:mft3