国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

幾種實用的pythonic語法實例代碼

2020-02-22 23:18:09
字體:
來源:轉載
供稿:網友

前言

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 子句

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 梅河口市| 玉门市| 金川县| 文成县| 乐安县| 东丰县| 银川市| 北碚区| 平利县| 高雄市| 扎鲁特旗| 鲁甸县| 湘潭市| 吉水县| 仪征市| 偏关县| 报价| 保康县| 庆安县| 花垣县| 达拉特旗| 镇坪县| 丰宁| 保山市| 清河县| 赣州市| 丹凤县| 剑河县| 临猗县| 溧阳市| 屏南县| 获嘉县| 曲沃县| 什邡市| 江安县| 财经| 焦作市| 海城市| 麻栗坡县| 邢台县| 东阳市|