前言
python 是一門簡單而優雅的語言,可能是過于簡單了,不用花太多時間學習就能使用,其實 python 里面還有一些很好的特性,能大大簡化你代碼的邏輯,提高代碼的可讀性。
所謂Pythonic,就是極具Python特色的Python代碼(明顯區別于其它語言的寫法的代碼)
關于 pythonic,你可以在終端打開 python,然后輸入 import this,看看輸出什么,這就是 Tim Peters 的 《The Zen of Python》,這首充滿詩意的詩篇里概況了 python 的設計哲學,而這些思想,其實在所有語言也基本上是通用的
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one– and preferably only one –obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea – let's do more of those!
使用生成器 yield
生成器是 python 里面一個非常有用的語法特性,卻也是最容易被忽視的一個,可能是因為大部分能用生成器的地方也能用列表吧。
生成器可以簡單理解成一個函數,每次執行到 yield 語句就返回一個值,通過不停地調用這個函數,就能獲取到所有的值,這些值就能構成了一個等效的列表,但是與列表不同的是,這些值是不斷計算得出,而列表是在一開始就計算好了,這就是 lazy evaluation 的思想。這個特性在數據量特別大的場景非常有用,比如大數據處理,一次無法加載所有的文件,使用生成器就能做到一行一行處理,而不用擔心內存溢出
def fibonacci(): num0 = 0 num1 = 1 for i in range(10): num2 = num0 + num1 yield num2 num0 = num1 num1 = num2for i in fibonacci(): print(i)
用 else 子句簡化循環和異常
if / else 大家都用過,但是在 python 里面,else 還可以用在循環和異常里面
# pythonic 寫法for cc in ['UK', 'ID', 'JP', 'US']: if cc == 'CN': breakelse: print('no CN')# 一般寫法no_cn = Truefor cc in ['UK', 'ID', 'JP', 'US']: if cc == 'CN': no_cn = False breakif no_cn: print('no CN')else 放在循環里面的含義是,如果循環全部遍歷完成,沒有執行 break,則執行 else 子句
新聞熱點
疑難解答