標籤:

我們為什麼要寫Pythonic代碼?

Pythonic means code that doesnt just get the syntax right but that follows the conventions of the Python community and uses the language in the way it is intended to be used.

我相信許多剛接觸Python的程序員, 特別是有別的語言基礎的, 有時候不理解為什麼要把代碼寫成Pythonic, 僅僅是因為美觀嗎? 下面幾張圖片告訴你原因:

1. 多使用內置函數

2. 使用列表解析式

3. ask forgiveness not permission

使用try/except 代替 if

4. 使用合適的數據結構

使用set做成員測試和去重

5. 避免生成不必要的數據

6. 避免不必要的函數調用

7. 避免不必要的bool測試

8. 使用語法糖

總結:

Pythonic 不僅使你的代碼更加優雅, 而且效率更高.

傳送門:

YouTube: youtube.com/watch?

PPT : switowski/europython2016

更多: 如何寫出優雅的Python代碼 - 知乎專欄


推薦閱讀:

第三章 字典和集合
從零開始寫Python爬蟲 --- 2.1 Scrapy 爬蟲框架的安裝與基本介紹
為啥別人能找到工作,而你不能?
Python面試指南

TAG:Python |