Python的22個編程技巧,Pick一下?
1. 原地交換兩個數(shù)字
Python 提供了一個直觀的在一行代碼中賦值與交換(變量值)的方法,請參見下面的示例:
- x,y= 10,20print(x,y)x,y= y,xprint(x,y)#1 (10, 20)#2 (20, 10)
賦值的右側(cè)形成了一個新的元組,左側(cè)立即解析(unpack)那個(未被引用的)元組到變量 和 。
一旦賦值完成,新的元組變成了未被引用狀態(tài)并且被標(biāo)記為可被垃圾回收,最終也完成了變量的交換。
2. 鏈狀比較操作符
比較操作符的聚合是另一個有時(shí)很方便的技巧:
- n= 10result= 1< n< 20print(result)# Trueresult= 1> n<= 9print(result)# False
3. 使用三元操作符來進(jìn)行條件賦值
三元操作符是 if-else 語句也就是條件操作符的一個快捷方式:
[表達(dá)式為真的返回值] if [表達(dá)式] else [表達(dá)式為假的返回值]
這里給出幾個你可以用來使代碼緊湊簡潔的例子。下面的語句是說“如果 y 是 9,給 x 賦值 10,不然賦值為 20”。如果需要的話我們也可以延長這條操作鏈。
- x = 10 if (y == 9) else 20
同樣地,我們可以對類做這種操作:
- x = (classA if y == 1 else classB)(param1, param2)
在上面的例子里 classA 與 classB 是兩個類,其中一個類的構(gòu)造函數(shù)會被調(diào)用。
下面是另一個多個條件表達(dá)式鏈接起來用以計(jì)算最小值的例子:
- def small(a,b,c):returnaifa<= banda<= celse(bifb<= aandb<= celsec)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
我們甚至可以在列表推導(dǎo)中使用三元運(yùn)算符:
- [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_rowwhere row_id < 5”print(multiStr)# select * from multi_row where row_id < 5
另一個技巧是使用三引號:
- multiStr= “””select * from multi_rowwhere row_id < 5″””print(multiStr)#select * from multi_row#where row_id < 5
上面方法共有的問題是缺少合適的縮進(jìn),如果我們嘗試縮進(jìn)會在字符串中插入空格。所以***的解決方案是將字符串分為多行并且將整個字符串包含在括號中:
- 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. 存儲列表元素到新的變量中
我們可以使用列表來初始化多個變量,在解析列表時(shí),變量的數(shù)目不應(yīng)該超過列表中的元素個數(shù):【譯者注:元素個數(shù)與列表長度應(yīng)該嚴(yán)格相同,不然會報(bào)錯】
- testList= [1,2,3]x,y,z= testListprint(x,y,z)#-> 1 2 3
6. 打印引入模塊的文件路徑
如果你想知道引用到代碼中模塊的絕對路徑,可以使用下面的技巧:
- import threadingimport socketprint(threading)print(socket)#1- #2-
7. 交互環(huán)境下的 “_” 操作符
這是一個我們大多數(shù)人不知道的有用特性,在 Python 控制臺,不論何時(shí)我們測試一個表達(dá)式或者調(diào)用一個方法,結(jié)果都會分配給一個臨時(shí)變量: _(一個下劃線)。
- >>> 2+ 13>>> _3>>> print_3
“_” 是上一個執(zhí)行的表達(dá)式的輸出。
8. 字典/集合推導(dǎo)
與我們使用的列表推導(dǎo)相似,我們也可以使用字典/集合推導(dǎo),它們使用起來簡單且有效,下面是一個例子:
- testDict= {i: i *iforiinxrange(10)}testSet= {i *2foriinxrange(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 中運(yùn)行上述代碼時(shí),將 改為 。
9. 調(diào)試腳本
我們可以在 模塊的幫助下在 Python 腳本中設(shè)置斷點(diǎn),下面是一個例子:
- import pdbpdb.set_trace()
我們可以在腳本中任何位置指定 并且在那里設(shè)置一個斷點(diǎn),相當(dāng)簡便。
10. 開啟文件分享
Python 允許運(yùn)行一個 HTTP 服務(wù)器來從根路徑共享文件,下面是開啟服務(wù)器的命令:
- # Python 2
- python -m SimpleHTTPServer
- # Python 3
- python3 -m http.server
上面的命令會在默認(rèn)端口也就是 8000 開啟一個服務(wù)器,你可以將一個自定義的端口號以***一個參數(shù)的方式傳遞到上面的命令中。
11. 檢查 Python 中的對象
我們可以通過調(diào)用 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 語句
我們可以使用下面的方式來驗(yàn)證多個值:
- 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]’,因?yàn)?set 中取元素是 O(1) 操作。
13. 一行代碼計(jì)算任何數(shù)的階乘
Python 2.x.
- result= (lambdak: reduce(int.__mul__,range(1,k+1),1))(3)print(result)#-> 6
Python 3.x.
- import functoolsresult= (lambdak: functools.reduce(int.__mul__,range(1,k+1),1))(3)print(result)#-> 6
14. 找到列表中出現(xiàn)最頻繁的數(shù)
- test= [1,2,3,4,2,2,3,1,4,4,4]print(max(set(test),key=test.count))#-> 4
15. 重置遞歸限制
Python 限制遞歸次數(shù)到 1000,我們可以重置這個值:
- import sysx=1001print(sys.getrecursionlimit())sys.setrecursionlimit(x)print(sys.getrecursionlimit())#1-> 1000#2-> 1001
請只在必要的時(shí)候采用上面的技巧。
16. 檢查一個對象的內(nèi)存使用
在 Python 2.7 中,一個 32 比特的整數(shù)占用 24 字節(jié),在 Python 3.5 中利用 28 字節(jié)。為確定內(nèi)存使用,我們可以調(diào)用 getsizeof 方法:
在 Python 2.7 中
- import sysx=1print(sys.getsizeof(x))#-> 24
在 Python 3.5 中
- import sysx=1print(sys.getsizeof(x))#-> 28
17. 使用 __slots__ 來減少內(nèi)存開支
你是否注意到你的 Python 應(yīng)用占用許多資源特別是內(nèi)存?有一個技巧是使用 __slots__ 類變量來在一定程度上減少內(nèi)存開支。
- import sysclassFileSystem(object):def __init__(self,files,folders,devices):self.files= filesself.folders= foldersself.devices= devicesprint(sys.getsizeof(FileSystem))classFileSystem1(object):__slots__= [‘files’,’folders’,’devices’]def __init__(self,files,folders,devices):self.files= filesself.folders= foldersself.devices= devicesprint(sys.getsizeof(FileSystem1))#In Python 3.5#1-> 1016#2-> 888
很明顯,你可以從結(jié)果中看到確實(shí)有內(nèi)存使用上的節(jié)省,但是你只應(yīng)該在一個類的內(nèi)存開銷不必要得大時(shí)才使用 __slots__。只在對應(yīng)用進(jìn)行性能分析后才使用它,不然地話,你只是使得代碼難以改變而沒有真正的益處。
【譯者注:在我的 win10 python2.7 中上面的結(jié)果是:
- #In Python 2.7 win10#1-> 896#2-> 1016
所以,這種比較方式是不那么讓人信服的,使用 __slots__ 主要是用以限定對象的屬性信息,另外,當(dāng)生成對象很多時(shí)花銷可能會小一些,具體可以參見 python 官方文檔:
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. 】
18. 使用 lambda 來模仿輸出方法
- import syslprint=lambda *args:sys.stdout.write(” “.join(map(str,args)))lprint(“python”,”tips”,1000,1001)#-> python tips 1000 1001
19.從兩個相關(guān)的序列構(gòu)建一個字典
- t1= (1,2,3)t2= (10,20,30)print(dict(zip(t1,t2)))#-> {1: 10, 2: 20, 3: 30}
20. 一行代碼搜索字符串的多個前后綴
- print(“http://www.google.com”.startswith((“http://”,”https://”)))print(“http://www.google.co.uk”.endswith((“.com”,”.co.uk”)))#1-> True#2-> True
21. 不使用循環(huán)構(gòu)造一個列表
- import itertoolstest= [[-1,-2],[30,40],[25,35]]print(list(itertools.chain.from_iterable(test)))#-> [-1, -2, 30, 40, 25, 35]
22. 在 Python 中實(shí)現(xiàn)一個真正的 switch-case 語句
下面的代碼使用一個字典來模擬構(gòu)造一個 switch-case。
- def xswitch(x):returnxswitch._system_dict.get(x,None)xswitch._system_dict= {‘files’: 10,’folders’: 5,’devices’: 2}print(xswitch(‘default’))print(xswitch(‘devices’))#1-> None#2-> 2