python實用30個小技巧
展開
1.原地交換兩個數字
Python 提供了一個直觀的在一行代碼中賦值與交換(變量值)的方法,請參見下面的示例:
In [1]: x,y = 10 ,20 In [2]: print(x,y) 10 20 In [3]: x, y = y, x In [4]: print(x,y) 20 10
賦值的右側形成了一個新的元組,左側立即解析(unpack)那個(未被引用的)元組到變量 <x> 和 <y>。
一旦賦值完成,新的元組變成了未被引用狀態並且被標記為可被垃圾回收,最終也完成了變量的交換。
2.鏈狀比較操作符
比較操作符的聚合是另一個有時很方便的技巧:
In [5]: n = 10 In [6]: result = 1 < n < 20 In [7]: result Out[7]: True In [8]: result = 1 > n <= 9 In [9]: result Out[9]: False
2.1、多個值符合條件判斷
常規寫法:
status_code = 0
if status_code == -1 or status_code == -2 or status_code == -3:
print('fail')
else:
print('success')
優雅寫法:
status_code = 0
if status_code in [-1, -2, -3]:
print('fail')
else:
print('success')
2.2、判斷是否為空
常規寫法:
A, B, C = [1, 2, 3], {}, ''
if len(A) > 0:
print('A非空')
if len(B) > 0:
print('B非空')
if len(C) > 0:
print('C非空')
優雅寫法:
A, B, C = [1, 2, 3], {}, ''
if A:
print('A非空')
if B:
print('B非空')
if C:
print('C非空')
2.3多條件判斷至少一個成立
常規寫法:
math, english, computer = 30, 90, 80
if math < 60 or english < 60 or computer < 60:
print('掛科')
else:
print('通過')
優雅寫法:
math, english, computer = 30, 90, 80
if any([math < 60, english < 60, computer < 60]):
print('掛科')
else:
print('通過')
2.4:多條件判斷內容全部成立
常規寫法:
math, english, computer = 70, 90, 80
if math > 60 and english > 60 and computer > 60:
print('通過')
else:
print('掛科')
優雅寫法:
math, english, computer = 70, 90, 80
if all([math > 60, english > 60, computer > 60]):
print('通過')
else:
print('掛科')
3.使用三元操作符來進行條件賦值
三元操作符是 if-else 語句也就是條件操作符的一個快捷方式:
[表達式為真的返回值] if [表達式] else [表達式為假的返回值]
這里給出幾個你可以用來使代碼緊湊簡潔的例子。下面的語句是說“如果 y 是 9,給 x 賦值 10,不然賦值為 20”。如果需要的話我們也可以延長這條操作鏈。
[on_true] if [expression] else [on_false]
x = 10 if (y == 9) else 20
同樣地,我們可以對類做這種操作:
x = (classA if y == 1 else classB)(param1, param2)
在上面的例子里 classA 與 classB 是兩個類,其中一個類的構造函數會被調用.
下面是另一個多個條件表達式鏈接起來用以計算最小值的例子:
In [10]: def small(a,b,c): ...: return a if a<=b and a<=c else ( b if b<=a and b<=c else c) ...: In [11]: small(1,0,1) Out[11]: 0 In [12]: small(1,2,3) Out[12]: 1 我們甚至可以在列表推導中使用三元運算符: In [14]: [ m**2 if m > 10 else m**4 for m in range(20) ] Out[14]: [0,1,16,81,256,625,1296,2401,4096,6561,10000,121,144,169,196,225,256,289,324,61]
4.多行字符串
基本的方式是使用源於 C 語言的反斜杠:
In [20]: multistr = " select * from multi_row \ ...: where row_id < 5" In [21]: multistr Out[21]: ' select * from multi_row where row_id < 5'
另一個技巧是使用三引號
In [23]: multistr ="""select * from multi_row ...: where row_id < 5""" In [24]: multistr Out[24]: 'select * from multi_row \nwhere row_id < 5'
上面方法共有的問題是缺少合適的縮進,如果我們嘗試縮進會在字符串中插入空格。所以最后的解決方案是將字符串分為多行並且將整個字符串包含在括號中:
In [25]: multistr = ("select * from multi_row "
...: "where row_id < 5 "
...: "order by age")
In [26]: multistr
Out[26]: 'select * from multi_row where row_id < 5 order by age'
5.存儲列表元素到新的變量中
我們可以使用列表來初始化多個變量,在解析列表時,變量的數目不應該超過列表中的元素個數:【譯者注:元素個數與列表長度應該嚴格相同,不然會報錯】
In [27]: testlist = [1,2,3] In [28]: x,y,z = testlist In [29]: print(x,y,z) 1 2 3
6.打印引入模塊的文件路徑
如果你想知道引用到代碼中模塊的絕對路徑,可以使用下面的技巧:
In [30]: import threading In [31]: import socket In [32]: print(threading) <module 'threading' from '/usr/local/lib/python3.5/threading.py'> In [33]: print(socket) <module 'socket' from '/usr/local/lib/python3.5/socket.py'>
7.交互環境下的"_"操作符
這是一個我們大多數人不知道的有用特性,在 Python 控制台,不論何時我們測試一個表達式或者調用一個方法,結果都會分配給一個臨時變量: _(一個下划線)。
In [34]: 2 + 3 Out[34]: 5 In [35]: _ Out[35]: 5 In [36]: print(_)
5
8.這是一個非常有用的功能,可惜很少人知道。
當你在交互界面敲代碼,獲得一個臨時結果,卻沒有用變量名去保存它的時候,可以用"_"來獲取最近一次臨時結果
“_” 是上一個執行的表達式的輸出。
8.字典/集合推導式
與我們使用的列表推導相似,我們也可以使用字典/集合推導,它們使用起來簡單且有效,下面是一個例子:
In [37]: testDict = {i : i*i for i in range(5)}
In [38]: testSet = { i*2 for i in range(5)}
In [39]: testDict
Out[39]: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
In [40]: testSet
Out[40]: {0, 2, 4, 6, 8}
配合enumerate:
iterable=[1,2,4,5,2]
set={i:item for (i,item) in enumerate(iterable)}
print(set) //{0: 1, 1: 2, 2: 4, 3: 5, 4: 2}
注:兩個語句中只有一個 <:> 的不同,另,在 Python3 中運行上述代碼時,將 <xrange> 改為 <range>。
9.調試腳本
我們可以在 <pdb> 模塊的幫助下在 Python 腳本中設置斷點,下面是一個例子:
import pdb pdb.set_trace()
我們可以在腳本中任何位置指定 <pdb.set_trace()> 並且在那里設置一個斷點,相當簡便。
10.開啟文件分享
Python 允許運行一個 HTTP 服務器來從根路徑共享文件,下面是開啟服務器的命令:(python3環境)
python3 -m http.server
上面的命令會在默認端口也就是 8000 開啟一個服務器,你可以將一個自定義的端口號以最后一個參數的方式傳遞到上面的命令中。
Paste_Image.png
11.檢查Python中的對象
我們可以通過調用 dir() 方法來檢查 Python 中的對象,下面是一個簡單的例子:
In [41]: test = [1,3,5,7] In [42]: print(dir(test)) ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
會列出對象的屬性方法。
12.簡化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) 操作。
13.運行時檢測Python版本
當正在運行的 Python 低於支持的版本時,有時我們也許不想運行我們的程序。為達到這個目標,你可以使用下面的代碼片段,它也以可讀的方式輸出當前 Python 版本:
import sys
#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,這是一個讀者的建議。
python3運行結果:
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]
14.組合多個字符串
如果你想拼接列表中的所有記號,比如下面的例子:
In [44]: test = ['I', 'Like', 'Python', 'automation'] In [45]: ''.join(test) Out[45]: 'ILikePythonautomation'
15.四種翻轉字符串/列表的方式
翻轉列表本身
In [49]: testList = [1, 3, 5] In [50]: testList.reverse() In [51]: testList Out[51]: [5, 3, 1]
在一個循環中翻轉並迭代輸出
In [52]: for element in reversed([1,3,5]): ...: print(element) ...: 5 3 1
一行代碼翻轉字符串
In [53]: "Test Python"[::-1] Out[53]: 'nohtyP tseT'
使用切片翻轉列表
[1, 3, 5][::-1]
16.玩轉枚舉
使用枚舉可以在循環中方便地找到(當前的)索引:
In [54]: testList= [10,20,30] In [55]: for i,value in enumerate(testList): ...: print(i,':',value) ...: 0 : 10 1 : 20 2 : 30
17.在python中使用枚舉量
我們可以使用下面的方式來定義枚舉量:
In [56]: class Shapes: ...: Circle,Square,Triangle,Quadrangle = range(4) ...: In [57]: Shapes.Circle Out[57]: 0 In [58]: Shapes.Square Out[58]: 1 In [59]: Shapes.Triangle Out[59]: 2 In [60]: Shapes.Quadrangle Out[60]: 3
18.從方法中返回多個值
並沒有太多編程語言支持這個特性,然而 Python 中的方法確實(可以)返回多個值,請參見下面的例子來看看這是如何工作的:
In [61]: def x(): ...: return 1,2,3,4 ...: In [62]: a,b,c,d = x() In [63]: print(a,b,c,d) 1 2 3 4
20.使用字典來存儲選擇操作
我們能構造一個字典來存儲表達式:
In [70]: stdacl = {
...: 'sum':lambda x,y : x + y,
...: 'subtract':lambda x,y : x - y
...: }
In [73]: stdacl['sum'](9,3)
Out[73]: 12
In [74]: stdacl['subtract'](9,3)
Out[74]: 6
21.一行代碼計算任何數的階乘
python3環境:
In [75]: import functools In [76]: result = ( lambda k : functools.reduce(int.__mul__,range(1,k+1),1))(3) In [77]: result Out[77]: 6
22.找到列表中出現最頻繁的數
In [82]: test = [1,2,3,4,2,2,3,1,4,4,4] In [83]: print(max(set(test),key=test.count)) 4
23.重置遞歸限制
Python 限制遞歸次數到 1000,我們可以重置這個值:
import sys x=1001 print(sys.getrecursionlimit()) sys.setrecursionlimit(x) print(sys.getrecursionlimit()) #1-> 1000 #2-> 100
謹慎修改
24.檢查一個對象的內存使用
在 Python 2.7 中,一個 32 比特的整數占用 24 字節,在 Python 3.5 中利用 28 字節。為確定內存使用,我們可以調用 getsizeof 方法:
python2.7: import sys x=1 print(sys.getsizeof(x)) #-> 24 python3: In [86]: import sys In [87]: x = 1 In [88]: sys.getsizeof(x) Out[88]: 28
25.使用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
很明顯,你可以從結果中看到確實有內存使用上的節省,但是你只應該在一個類的內存開銷不必要得大時才使用 slots。只在對應用進行性能分析后才使用它,不然地話,你只是使得代碼難以改變而沒有真正的益處。
26.使用lambda來模仿輸出方法
In [89]: import sys
In [90]: lprint = lambda *args: sys.stdout.write("".join(map(str,args)))
In [91]: lprint("python","tips",1000,1001)
Out[91]: pythontips1000100118
27.從兩個相關的序列構建一個字典
In [92]: t1 = (1,2,3)
In [93]: t2 =(10,20,30)
In [94]: dict(zip(t1,t2))
Out[94]: {1: 10, 2: 20, 3: 30}
28.一行代碼搜索字符串的多個前后綴
In [95]: print("http://www.google.com".startswith(("http://", "https://")))
True
In [96]: print("http://www.google.co.uk".endswith((".com", ".co.uk")))
True
29. 不使用循環構造一個列表
In [101]: test = [[-1, -2], [30, 40], [25, 35]] In [102]: import itertools In [103]: print(list(itertools.chain.from_iterable(test))) [-1, -2, 30, 40, 25, 35]
30.在Python中實現一個真正的switch-case語句
下面的代碼使用一個字典來模擬構造一個switch-case。
In [104]: def xswitch(x):
...: return xswitch._system_dict.get(x, None)
...:
In [105]: xswitch._system_dict = {'files': 10, 'folders': 5, 'devices': 2}
In [106]: print(xswitch('default'))
None
In [107]: print(xswitch('devices'))
作者:海賊之路飛
鏈接:https://www.jianshu.com/p/cdceff697af8
31
強制浮點數除法
如果我們除以一個整數,即使結果是一個浮點數,Python(2) 依舊會給我們一個整數。為了規避這個問題,我們需要這樣做:
result = 1.0/2
但是現在有一種別的方法可以解決這個問題,甚至在之前我都沒有意識到有這種方法存在。你可以進行如下操作:
from __future__ import division result = 1/2 # print(result) # 0.5
需要注意的是這個竅門只適用於Python 2。在Python 3 中就不需要進行import 操作了,因為它已經默認進行import了。
列表推導式
常規寫法:
nums = [] for i in range(10): nums.append(i) print(nums) # output: # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
優雅寫法:
nums = [i for i in range(10)] print(nums) # output: # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
4. with - as
with 這個詞兒,英文里面不難翻譯,但在 Python 語法中怎么翻譯,我還真想不出來,大致上是一種上下文管理協議。作為初學者,不用關注 with 的各種方法以及機制如何,只需要了解它的應用場景就可以了。with 語句適合一些事先需要准備,事后需要處理的任務,比如,文件操作,需要先打開文件,操作完成后需要關閉文件。如果不使用with,文件操作通常得這樣:
fp = open(r"D:\CSDN\Column\temp\mpmap.py", 'r') try: contents = fp.readlines() finally: fp.close()
如果使用 with - as,那就優雅多了:
with open(r"D:\CSDN\Column\temp\mpmap.py", 'r') as fp: contents = fp.readlines()
遍歷字典
d1={'sdf':22,'sdfs':'sdfs'}
d1
{'sdf': 22, 'sdfs': 'sdfs'}
for key,value in d1.items():
print(key,value)
sdf 22
sdfs sdfs
