Python 程式碼最佳化技巧?
雖然我們都知道 Python 的速度和效率不如其他編譯型語言。但是,許多大型公司向我們展示了 Python 程式碼可以處理更大的工作負載,這表明它並不慢。在本節中,我們將瞭解一些應該牢記的技巧,以便正確的 Python 程式執行得更快、更高效。
技巧 1:使用內建函式
雖然我們可以在 Python 中編寫高效的程式碼,但很難超越內建函式(用 C 語言編寫)。下圖顯示了 Python 內建函式的列表。
技巧 2:使用 Python 多重賦值交換變數
>>> #Instead of using >>> x, y = y, x >>> #Use this - which is much faster >>> temp = x >>> x = y >>> y = temp
技巧 3:避免使用全域性變數,如果可能,使用區域性變數
在檢索區域性變數時,Python 比檢索全域性變數快。也就是說,如果可能,避免使用全域性變數。
技巧 4:儘可能使用 “in”
要檢查成員資格,請使用 “in” 關鍵字。它簡潔且快速。
for key in sequence: print ("Hello ", key)
技巧 5:使用 “while 1” 進行無限迴圈
有時我們需要在程式中執行無限迴圈(例如,偵聽套接字)。雖然 “while True” 會執行相同的操作,但 “while 1” 只是一個簡單的跳轉操作。
>>> while 1: # do something, faster with while 1 >>> while True: #do something, perform same operation but slower than then previous one
技巧 6:使用列表推導式
從 Python 2.0 開始,我們可以使用列表推導式來替換許多 “for” 和 “while” 程式碼塊。列表推導式速度更快,因為它經過最佳化,Python 直譯器可以在迴圈過程中識別可預測的模式。它更易讀,並且在大多數情況下,它可以節省一個用於計數的額外變數。
例如,用一行程式碼查詢 1 到 25 之間的偶數
>>> #Using list comprehension - good way >>> print([i for i in range (25) if i%2 == 0]) [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24] >>> # Another way - not so efficient way i = 0 evens = [] while i< 25: if i%2 == 0: evens.append(i) i += 1 print(evens) [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24]
技巧 7:使用 Python 生成器按需獲取值
使用 Python 生成器可以節省記憶體並提高效能。如果您正在流式傳輸影片,則可以傳送位元組塊,而不是整個流。
>>> chunkBytes = (1000 * i for i in range(1000)) >>> next(chunkBytes) 0 >>> next(chunkBytes) 1000 >>> next(chunkBytes) 2000 >>> next(chunkBytes) 3000 >>>
技巧 8:使用 itertools 模組
itertools 模組對於迭代和組合非常有用且高效。
用幾行 Python 程式碼生成列表 [1, 2, 3, 4, 5] 的所有排列
>>> import itertools >>> iter1 = itertools.permutations([1, 2, 3,4]) >>> list(iter1) [(1, 2, 3, 4), (1, 2, 4, 3), (1, 3, 2, 4), (1, 3, 4, 2), (1, 4, 2, 3), (1, 4, 3, 2), (2, 1, 3, 4), (2, 1, 4, 3), (2, 3, 1, 4), (2, 3, 4, 1), (2, 4, 1, 3), (2, 4, 3, 1), (3, 1, 2, 4), (3, 1, 4, 2), (3, 2, 1, 4), (3, 2, 4, 1), (3, 4, 1, 2), (3, 4, 2, 1), (4, 1, 2, 3), (4, 1, 3, 2), (4, 2, 1, 3), (4, 2, 3, 1), (4, 3, 1, 2), (4, 3, 2, 1)]
技巧 9:使用 bisect 模組保持列表排序
它是一個免費的二分查詢實現,也是排序序列的快速插入工具。
>>> import bisect >>> bisect.insort(list, element)
我們將元素插入到列表中,現在無需再次呼叫 sort() 來保持容器排序,這在長序列上可能非常耗時。
技巧 10:使用字典和集合測試成員資格
由於字典和集合是使用雜湊表實現的,因此檢查元素是否在字典或集合中存在於 Python 中非常快。有時查詢速度可以達到 O(1)。
>>> lst = ['a', 'ab', 'abc'] #Slow - Checking membership with list >>> 'abc' in lst True >>> mySet = set(['a', 'ab', 'abc'])# Fast - checking membership with set or dictionary >>> 'abc' in mySet True
技巧 11:使用 Python 裝飾器快取結果
Python 裝飾器符號是 “@”。我們可以使用 Python 裝飾器不僅用於跟蹤、鎖定或記錄,還可以用來裝飾 Python 函式,以便它記住以後需要的結果(記憶化)。
>>> from functools import wraps >>> def memo(f): cache = {} @wraps(f) def wrap(*arg): if arg not in cache: cache['arg'] = f(*arg) return cache['arg'] return wrap
我們可以將此裝飾器用於斐波那契函式
>>> @memo def fib(i): if i<2: return 1 return fib(i-1) + fib(i-2)
基本思想是增強(裝飾)您的函式,以便記住您計算的每個斐波那契項,如果它們在快取中,則無需再次計算。