直接交換2個數字的位置 Python 提供了一種直觀的方式在一行代碼中賦值和交換(變量值)。如下所示:
x, y = 10, 20 print(x, y) x, y = y, x print(x, y) #1 (10, 20) #2 (20, 10)
在上面代碼中,賦值的右側形成了一個新元組,而左側則立刻將該(未被引用的)元組解包到名稱<a>和<b>。
待賦值完成後,新元組就變成了未被引用狀態,並且被標爲可被垃圾回收,最終也就發生了數字交換。
鏈接比較操作符 比較運算符的聚合是另一種有時用起來很順手的技巧。
n = 10 result = 1 < n < 20 print(result) # True result = 1 > n <= 9 print(result) # False
使用三元操作符進行條件賦值 三元操作符是 if-else 語句(也就是條件操作符)的快捷操作:
[on_true] if [expression] else [on_false]
下面舉兩個例子例子,展示一下可以用這種技巧讓你的代碼更緊湊更簡潔。
下面的語句意思是“如果 y 爲 9,就向 x 賦值 10,否則向 x 賦值 20”。如果需要,我們可以擴展這個操作符鏈接:
x = 10 if (y == 9) else 20
同樣,我們對類對象也可以這樣操作:
x = (classA if y == 1 else classB)(param1, param2)
在上面這個例子中,classA 與 classB 是兩個類,其中一個類構造函數會被調用。
使用多行字符串 這個方法就是使用源自 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
將一個列表的元素保存到新變量中 我們可以用一個列表來初始化多個變量,在解析列表時,變量的數量不應超過列表中的元素數量,否則會報錯。
testList = [1,2,3] x, y, z = testList print(x, y, z) #-> 1 2 3
打印出導入的模塊的文件路徑 如果你想知道代碼中導入的模塊的絕對路徑,用下面這條技巧就行了:
import threading import socket print(threading) print(socket) #1- <module 'threading' from '/usr/lib/python2.7/threading.py'> #2- <module 'socket' from '/usr/lib/python2.7/socket.py'>
使用交互式“_”操作符 其實這是個相當有用的功能,只是我們很多人並沒有注意到。
在 Python 控制檯中,每當我們測試一個表達式或調用一個函數時,結果都會分配一個臨時名稱,_(一條下劃線)。
>>> 2 + 1 3 >>> _ 3 >>> print _ 3
這裏的“_”是上一個執行的表達式的結果。
字典/集合推導 就像我們使用列表表達式一樣,我們也可以使用字典/集合推導。非常簡單易用,也很有效,示例如下:
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>
。
調試腳本
我們可以藉助 <pdb>
模塊在 Python 腳本中設置斷點,如下所示:
import pdb pdb.set_trace()
我們可以在腳本的任意位置指定<pdb.set_trace()> ,然後在那裏設置一個斷點,非常方便。
設置文件分享 Python 能讓我們運行 HTTP 服務器,可以用於分享服務器根目錄中的文件。啓動服務器的命令如下:
# Python 2: python -m SimpleHTTPServer # Python 3: python3 -m http.server
上述命令會在默認端口 8000 啓動一個服務器,你也可以使用自定義端口,將端口作爲最後元素傳入上述命令中即可。
在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']
簡化if語句
我們可以通過如下方式來驗證多個值:
if m in [1,3,5,7]:
而不用這樣:
if m==1 or m==3 or m==5 or m==7:
對於in操作符,我們也可以用‘{1,3,5,7}’而不是‘[1,3,5,7]’,因爲‘set’可以通過O(1)獲取每個元素。
在運行時檢測Python的版本 有時如果當前運行的 Python 低於支持版本時,我們可能不想執行程序。那麼就可以用下面的代碼腳本檢測 Python 的版本。還能以可讀格式打印出當前所用的 Python 版本。
import sys #檢測當前所用的Python版本 if not hasattr(sys, "hexversion") or sys.hexversion != 50660080: print("Sorry, you aren't running on Python 3.5\n") print("Please upgrade to 3.5.\n") sys.exit(1) #以可讀格式打印出Python版本 print("Current Python version: ", sys.version) 另外,你可以將上面代碼中的 sys.hexversion!= 50660080 替換爲 sys.version_info >= (3, 5)。
在 Python 2.7 中運行輸出爲:
Python 2.7.10 (default, Jul 14 2015, 19:46:27) [GCC 4.8.2] on linux Sorry, you aren't running on Python 3.5 Please upgrade to 3.5.
在Python 3.5中運行輸出爲:
Python 3.5.1 (default, Dec 2015, 13:05:11) [GCC 4.8.2] on linux Current Python version: 3.5.2 (default, Aug 22 2016, 21:11:05) [GCC 5.3.0]
組合多個字符串 如果你想拼接列表中的所有 token,那麼看看下面的例子就明白了:
>>> test = ['I', 'Like', 'Python', 'automation']
現在我們從上面列表的元素中創建一個字符串:
>>> print ''.join(test)
翻轉字符串/列表的4種方式
#翻轉列表本身 testList = [1, 3, 5] testList.reverse() print(testList) #-> [5, 3, 1] #在循環中迭代時翻轉 for element in reversed([1,3,5]): print(element) #1-> 5 #2-> 3 #3-> 1 #翻轉一行代碼中的字符串 "Test Python"[::-1]
我們會得到結果“nohtyP tseT”。
#用切片翻轉一個列表 [1, 3, 5][::-1]
上面的命令會得到輸出結果 [5, 3, 1]。
使用枚舉 使用枚舉可以很容易地在循環中找到索引:
testlist = [10, 20, 30] for i, value in enumerate(testlist): print(i, ': ', value) #1-> 0 : 10 #2-> 1 : 20 #3-> 2 : 30 在 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
從函數中返回多個值
支持這種功能的編程語言並不多,然而,Python 中的函數可以返回多個值。
可以參考下面的例子看看是怎麼做到的:
# 返回多個值的函數 def x(): return 1, 2, 3, 4 # 調用上面的函數 a, b, c, d = x() print(a, b, c, d) #-> 1 2 3 4
使用*運算符解壓縮函數參數
運算符提供了一種很藝術的方式來解壓縮參數列表,參看如下示例:
def test(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
使用字典來存儲表達式
stdcalc = { 'sum': lambda x, y: x + y, 'subtract': lambda x, y: x - y } print(stdcalc['sum'](9,3)) print(stdcalc['subtract'](9,3)) #1-> 12 #2-> 6
一行代碼計算任何數字的階乘
# Python 2.X result = (lambda k: reduce(int.__mul__, range(1,k+1),1))(3) print(result) #-> 6 # Python 3.X import functools result = (lambda k: functools.reduce(int.__mul__, range(1,k+1),1))(3) print(result) #-> 6
找到一個列表中的出現最頻繁的值
test = [1,2,3,4,2,2,3,1,4,4,4] print(max(set(test), key=test.count)) #-> 4 重置遞歸限制 Python 將遞歸限制到 1000,我們可以重置這個值: import sys x=1001 print(sys.getrecursionlimit()) sys.setrecursionlimit(x) print(sys.getrecursionlimit()) #1-> 1000 #2-> 1001
提示:在有必要時才使用該技巧。
檢查一個對象的內存使用 在 Python 2.7 中,一個 32-bit 的整數值會佔用 24 字節,而在 Python 3.5 中會佔用 28 字節。我們可以調用<getsizeof> 方法來驗證內存使用。
在 Python 2.7 中:
import sys x=1 print(sys.getsizeof(x)) #-> 24
在 Python 3.5 中:
import sys x=1 print(sys.getsizeof(x)) #-> 28
使用slots減少內存消耗
不知道你是否注意過你的 Python 程序會佔用很多資源,特別是內存?這裏分享給你一個技巧,使用 <slots> 類變量來減少程序的內存消耗。
import sys class 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
很明顯,從解僱中可以看到節省了一些內存。但是應當在一個類的內存佔用大得沒有必要時再使用這種方法。對應用進行性能分析後再使用它,不然除了會讓代碼難以改動外沒有什麼好處。
使用拉姆達來模仿輸出方法
import sys lprint=lambda *args:sys.stdout.write(" ".join(map(str,args))) lprint("python", "tips",1000,1001) #-> python tips 1000 1001
從兩個相關序列中創建一個字典
t1 = (1, 2, 3) t2 = (10, 20, 30) print(dict (zip(t1,t2))) #-> {1: 10, 2: 20, 3: 30}
用一行代碼搜索字符串的前後綴
print("http://www.google.com".startswith(("http://", "https://"))) print("http://www.google.co.uk".endswith((".com", ".co.uk"))) #1-> True #2-> True
不使用任何循環,構造一個列表
import itertools test = [[-1, -2], [30, 40], [25, 35]] print(list(itertools.chain.from_iterable(test))) #-> [-1, -2, 30, 40, 25, 35]
如果輸入列表中有嵌入的列表或元組作爲元素,那麼就使用下面這種方法,不過也有個侷限,它使用了 for 循環:
def unifylist(l_input, l_target): for it in l_input: if isinstance(it, list): unifylist(it, l_target) elif isinstance(it, tuple): unifylist(list(it), l_target) else: l_target.append(it) return l_target test = [[-1, -2], [1,2,3, [4,(5,[6,7])]], (30, 40), [25, 35]] print(unifylist(test,[])) #Output => [-1, -2, 1, 2, 3, 4, 5, 6, 7, 30, 40, 25, 35]
在Python中實現一個真正的switch-case語句
下面是使用字典模仿一個 switch-case 構造的代碼示例:
def xswitch(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 開發,可以在項目中應用它們。