国产探花免费观看_亚洲丰满少妇自慰呻吟_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 子句

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 韩城市| 宁明县| 隆林| 巩留县| 邢台县| 神池县| 惠州市| 河曲县| 社旗县| 正镶白旗| 介休市| 东阿县| 通山县| 南溪县| 平塘县| 贺兰县| 陵水| 澄迈县| 鄂尔多斯市| 宜良县| 应城市| 玉龙| 汝城县| 皋兰县| 左云县| 涡阳县| 保亭| 同德县| 绥芬河市| 鲁山县| 城固县| 阳山县| 澄江县| 屯门区| 石渠县| 宁阳县| 哈密市| 和平区| 郯城县| 泰顺县| 丹江口市|