search
尋找貓咪~QQ 地點 桃園市桃園區 Taoyuan , Taoyuan

Python 程序員需要知道的 30 個技巧

如果你讓一個 Python 程序員說一下 Python 的優勢,他會說簡潔以及高可讀是最有影響力的優勢。為證明上述兩點,在這個 Python 教程里,我們將聊聊許多基本的 Python 建議和技巧。

Python學習交流群:639584010

我們從開始使用 Python 便收集這些有用的捷徑(貼士與技巧)。分享一些我們知道,同時又能造福於人的知識,有什麼事情比這更棒嗎?

所以今天我們帶來另一些基本的 Python 貼士與技巧,所有的這些技巧都能幫助你壓縮代碼並且優化運行。此外,你可以在日常工作中很容易地在真實項目中使用他們。

每一個技巧都有一個示例並且給出簡短的解釋,如果要測試這些代碼片段,你可以看一下這些 在線虛擬 Python 運行終端

使用下面的 TOC 來快速地瀏覽這些 Python 貼士與技巧。

給程序員的 30 個基本 Python 貼士與技巧

貼士#1. 原地交換兩個數字

Python 提供了一個直觀的在一行代碼中賦值與交換(變數值)的方法,請參見下面的示例:

x, y = 10, 20print(x, y) x, y = y, x print(x, y) #1 (10, 20)#2 (20, 10)

賦值的右側形成了一個新的元組,左側立即解析(unpack)那個(未被引用的)元組到變數 <a> 和 <b> 。

一旦賦值完成,新的元組變成了未被引用狀態並且被標記為可被垃圾回收,最終也完成了變數的交換。

貼士#2. 鏈狀比較操作符

比較操作符的聚合是另一個有時很方便的技巧:

n = 10result = 1 < n < 20print(result) # True result = 1 > n <= 9print(result) # False

貼士#3. 使用三元操作符來進行條件賦值

三元操作符是 if-else 語句也就是條件操作符的一個快捷方式:

[表達式為真的返回值] if [表達式] else [表達式為假的返回值]

這裡給出幾個你可以用來使代碼緊湊簡潔的例子。下面的語句是說「如果 y 是 9,給 x 賦值 10,不然賦值為 20」。如果需要的話我們也可以延長這條操作鏈。

x = 10 if (y == 9) else 20

同樣地,我們可以對類做這種操作:

x = (classAif y == 1 else classB)(param1, param2)

在上面的例子里 classA 與 classB 是兩個類,其中一個類的構造函數會被調用。

下面是另一個多個條件表達式鏈接起來用以計算最小值的例子:

defsmall(a, b, c): return a if a <= b and a <= c else (b if b <= a and b <= c else c) print(small(1, 0, 1)) print(small(1, 2, 2)) print(small(2, 2, 3)) print(small(5, 4, 3)) #Output#0 #1 #2 #3

我們甚至可以在列表推導中使用三元運算符:

[m**2 if m > 10 else m**4 for m in range(50)] #=> [0, 1, 16, 81, 256, 625, 1296, 2401, 4096, 6561, 10000, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625, 676, 729, 784, 841, 900, 961, 1024, 1089, 1156, 1225, 1296, 1369, 1444, 1521, 1600, 1681, 1764, 1849, 1936, 2025, 2116, 2209, 2304, 2401]

貼士#4. 多行字元串

基本的方式是使用源於 C 語言的反斜杠:

multiStr = "select * from multi_row where row_id < 5"print(multiStr) # select * from multi_row where row_id < 5

另一個技巧是使用三引號:

multiStr = """select * from multi_row where row_id < 5"""print(multiStr) #select * from multi_row#where row_id < 5

上面方法共有的問題是缺少合適的縮進,如果我們嘗試縮進會在字元串中插入空格。所以最後的解決方案是將字元串分為多行並且將整個字元串包含在括弧中:

multiStr= ("select * from multi_row ""where row_id < 5 ""order by age") print(multiStr) #select * from multi_row where row_id < 5 order by age

貼士#5. 存儲列表元素到新的變數中

我們可以使用列表來初始化多個變數,在解析列表時,變數的數目不應該超過列表中的元素個數:【譯者註:元素個數與列表長度應該嚴格相同,不然會報錯】

testList = [123] x, y, z = testList print(x, y, z) #-> 1 2 3

貼士#6. 列印引入模塊的文件路徑

如果你想知道引用到代碼中模塊的絕對路徑,可以使用下面的技巧:

importthreading importsocket print(threading) print(socket) #1- <module 'threading' from '/usr/lib/python2.7/threading.py'>#2- <module 'socket' from '/usr/lib/python2.7/socket.py'>

貼士#7. 交互環境下的 「_」 操作符

這是一個我們大多數人不知道的有用特性,在 Python 控制台,不論何時我們測試一個表達式或者調用一個方法,結果都會分配給一個臨時變數: _ (一個下劃線)。

>>> 2 + 13>>> _3>>> print _3

「_」 是上一個執行的表達式的輸出。

貼士#8. 字典/集合推導

與我們使用的列表推導相似,我們也可以使用字典/集合推導,它們使用起來簡單且有效,下面是一個例子:

testDict = {i: i * i for i in xrange(10)} testSet = {i * 2 for i in xrange(10)} print(testSet) print(testDict) #set([0, 2, 4, 6, 8, 10, 12, 14, 16, 18])#{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

註:兩個語句中只有一個 <:> 的不同,另,在 Python3 中運行上述代碼時,將 <xrange> 改為 <range> 。

貼士#9. 調試腳本

我們可以在 <pdb> 模塊的幫助下在 Python 腳本中設置斷點,下面是一個例子:

importpdb pdb.set_trace

我們可以在腳本中任何位置指定 <pdb.set_trace> 並且在那裡設置一個斷點,相當簡便。

貼士#10. 開啟文件分享

Python 允許運行一個 HTTP 伺服器來從根路徑共享文件,下面是開啟伺服器的命令:

# Python 2python -m SimpleHTTPServer# Python 3python3 -m http.server

上面的命令會在默認埠也就是 8000 開啟一個伺服器,你可以將一個自定義的埠號以最後一個參數的方式傳遞到上面的命令中。

貼士#11. 檢查 Python 中的對象

我們可以通過調用 dir 方法來檢查 Python 中的對象,下面是一個簡單的例子:

test = [1, 3, 5, 7] print( dir(test) )['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

貼士#12. 簡化 if 語句

我們可以使用下面的方式來驗證多個值:

if m in [1357]:

而不是:

if m==1 or m==3 or m==5 or m==7:

或者,對於 in 操作符我們也可以使用 '{1,3,5,7}' 而不是 '[1,3,5,7]' ,因為 set 中取元素是 O(1) 操作。

貼士#13. 運行時檢測 Python 版本

當正在運行的 Python 低於支持的版本時,有時我們也許不想運行我們的程序。為達到這個目標,你可以使用下面的代碼片段,它也以可讀的方式輸出當前 Python 版本:

importsys #Detect the Python version currently in use.if not hasattr(sys, "hexversion") or sys.hexversion != 50660080: print("Sorry, you aren't running on Python 3.5n") print("Please upgrade to 3.5.n") sys.exit(1) #Print Python version in a readable format.print("Current Python version: ", sys.version)

或者你可以使用 sys.version_info >= (3, 5) 來替換上面代碼中的 sys.hexversion != 50660080 ,這是一個讀者的建議。

在 Python 2.7 上運行的結果:

Python 2.7.10 (default, Jul 14 2015, 19:46:27) [GCC 4.8.2] onlinux Sorry, youaren't runningonPython 3.5 Pleaseupgradeto 3.5.

在 Python 3.5 上運行的結果:

Python 3.5.1 (default, Dec 2015, 13:05:11) [GCC 4.8.2] onlinux CurrentPythonversion: 3.5.2 (default, Aug 22 2016, 21:11:05) [GCC 5.3.0]

貼士#14. 組合多個字元串

如果你想拼接列表中的所有記號,比如下面的例子:

>>> test = ['I', 'Like', 'Python', 'automation']

現在,讓我們從上面給出的列表元素新建一個字元串:

>>> print ''.join(test)

貼士#15. 四種翻轉字元串/列表的方式

# 翻轉列表本身testList = [1, 3, 5] testList.reverse print(testList) #-> [5, 3, 1]# 在一個循環中翻轉并迭代輸出for elementin reversed([135]): print(element) #1-> 5#2-> 3#3-> 1# 一行代碼翻轉字元串"Test Python"[::-1]

輸出為 「nohtyP tseT」

# 使用切片翻轉列表[1, 3, 5][::-1]

上面的命令將會給出輸出 [5,3,1]。

貼士#16. 玩轉枚舉

使用枚舉可以在循環中方便地找到(當前的)索引:

testlist = [10, 20, 30]for i, valuein enumerate(testlist): print(i, ': ', value) #1-> 0 : 10#2-> 1 : 20#3-> 2 : 30

貼士#17. 在 Python 中使用枚舉量

我們可以使用下面的方式來定義枚舉量:

class Shapes: Circle, Square, Triangle, Quadrangle = range(4) print(Shapes.Circle) print(Shapes.Square) print(Shapes.Triangle) print(Shapes.Quadrangle) #1-> 0#2-> 1#3-> 2#4-> 3

貼士#18. 從方法中返回多個值

並沒有太多編程語言支持這個特性,然而 Python 中的方法確實(可以)返回多個值,請參見下面的例子來看看這是如何工作的:

# function returning multiple values.def x: return 1, 2, 3, 4 # Calling the above function.a, b, c, d = x print(a, b, c, d) #-> 1 2 3 4

貼士#19. 使用 * 運算符(splat operator)來 unpack 函數參數

* 運算符(splat operator)提供了一個藝術化的方法來 unpack 參數列表,為清楚起見請參見下面的例子:

deftest(x, y, z): print(x, y, z) testDict = {'x': 1, 'y': 2, 'z': 3} testList = [10, 20, 30] test(*testDict) test(**testDict) test(*testList) #1-> x y z#2-> 1 2 3#3-> 10 20 30

貼士#20. 使用字典來存儲選擇操作

我們能構造一個字典來存儲表達式:

stdcalc = { 'sum': lambda x, y: x + y, 'subtract': lambda x, y: x - y } print(stdcalc['sum'](93)) print(stdcalc['subtract'](93)) #1-> 12#2-> 6

貼士#21. 一行代碼計算任何數的階乘

Python 2.x.result = (lambda k: reduce(int.__mul__, range(1,k+1),1))(3) print(result) #-> 6Python 3.x.importfunctools result = (lambda k: functools.reduce(int.__mul__, range(1,k+1),1))(3) print(result) #-> 6

貼士#22. 找到列表中出現最頻繁的數

test = [12342231444] print(max(set(test), key=test.count)) #-> 4

貼士#23. 重置遞歸限制

Python 限制遞歸次數到 1000,我們可以重置這個值:

importsys x=1001print(sys.getrecursionlimit) sys.setrecursionlimit(x) print(sys.getrecursionlimit) #1-> 1000#2-> 1001

請只在必要的時候採用上面的技巧。

貼士#24. 檢查一個對象的內存使用

在 Python 2.7 中,一個 32 比特的整數佔用 24 位元組,在 Python 3.5 中利用 28 位元組。為確定內存使用,我們可以調用 getsizeof 方法:

在 Python 2.7 中importsys x=1print(sys.getsizeof(x)) #-> 24在 Python 3.5 中importsys x=1print(sys.getsizeof(x)) #-> 28

貼士#25. 使用 __slots__ 來減少內存開支

你是否注意到你的 Python 應用佔用許多資源特別是內存?有一個技巧是使用 __slots__ 類變數來在一定程度上減少內存開支。

importsysclass FileSystem(object): def__init__(self, files, folders, devices): self.files = files self.folders = folders self.devices = devices print(sys.getsizeof( FileSystem )) class FileSystem1(object): __slots__ = ['files', 'folders', 'devices'] def__init__(self, files, folders, devices): self.files = files self.folders = folders self.devices = devices print(sys.getsizeof( FileSystem1 ))#In Python 3.5#1-> 1016#2-> 888

很明顯,你可以從結果中看到確實有內存使用上的節省,但是你只應該在一個類的內存開銷不必要得大時才使用 __slots__ 。只在對應用進行性能分析后才使用它,不然地話,你只是使得代碼難以改變而沒有真正的益處。

【譯者註:在我的 win10 python2.7 中上面的結果是:

#In Python 2.7 win10#1-> 896#2-> 1016

所以,這種比較方式是不那麼讓人信服的,使用 __slots__ 主要是用以限定對象的屬性信息,另外,當生成對象很多時花銷可能會小一些

The slots declaration takes a sequence of instance variables and reserves just enough space in each instance to hold a value for each variable. Space is saved because dict is not created for each instance. 】

貼士#26. 使用 lambda 來模仿輸出方法

importsys lprint=lambda *args:sys.stdout.write(" ".join(map(str,args))) lprint("python", "tips"10001001) #-> python tips 1000 1001

貼士#27. 從兩個相關的序列構建一個字典

t1 = (1, 2, 3) t2 = (10, 20, 30) print(dict (zip(t1,t2))) #-> {1: 10, 2: 20, 3: 30}

貼士#28. 一行代碼搜索字元串的多個前後綴

print("http://www.google.com".startswith(("http://", "https://"))) print("http://www.google.co.uk".endswith((".com", ".co.uk"))) #1-> True#2-> True

貼士#29. 不使用循環構造一個列表

importitertools test = [[-1, -2], [30, 40], [25, 35]] print(list(itertools.chain.from_iterable(test))) #-> [-1, -2, 30, 40, 25, 35]

貼士#30. 在 Python 中實現一個真正的 switch-case 語句

下面的代碼使用一個字典來模擬構造一個 switch-case。

defxswitch(x): return xswitch._system_dict.get(x, None) xswitch._system_dict = {'files': 10, 'folders': 5, 'devices': 2} print(xswitch('default')) print(xswitch('devices')) #1-> None#2-> 2

結語 – 給程序員的基本 Python 貼士與技巧

我們希望上述的基本的 Python 貼士與技巧可以幫助你快速地 & 有效地完成任務,你可以在作業與項目中使用他們。

聽從你的回饋會使我們變得更好,所以請分享你的想法。



熱門推薦

本文由 yidianzixun 提供 原文連結

寵物協尋 相信 終究能找到回家的路
寫了7763篇文章,獲得2次喜歡
留言回覆
回覆
精彩推薦