Python的22個編程技巧,簡化 if 語句、開啓文件分享……

1. 原地交換兩個數字

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

x,y= 10,20

print(x,y)

x,y= y,x

print(x,y)

#1 (10, 20)

#2 (20, 10)

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

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

2. 鏈狀比較操作符

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

n= 10

result= 1< n< 20

print(result)

# True

result= 1> n<= 9

print(result)

# False

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

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

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

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

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

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

x = (classA if y == 1 else classB)(param1, param2)

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

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

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

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

[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= [1,2,3]

x,y,z= testList

print(x,y,z)

#-> 1 2 3

6. 打印引入模塊的文件路徑

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

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’>

7. 交互環境下的 “_” 操作符

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


>>> 2+ 1

3

>>> _

3

>>> print_

3

“_” 是上一個執行的表達式的輸出。

8. 字典/集合推導

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

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 中運行上述代碼時,將 <xrange> 改爲 <range>。

9. 調試腳本

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

import pdb

pdb.set_trace()

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

10. 開啓文件分享

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

# Python 2

python -m SimpleHTTPServer

# Python 3

python3 -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 [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 2.x.

result= (lambdak: reduce(int.__mul__,range(1,k+1),1))(3)

print(result)

#-> 6

Python 3.x.

import functools

result= (lambdak: functools.reduce(int.__mul__,range(1,k+1),1))(3)

print(result)

#-> 6

14. 找到列表中出現最頻繁的數

test= [1,2,3,4,2,2,3,1,4,4,4]

print(max(set(test),key=test.count))

#-> 4

15. 重置遞歸限制

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

import sys

x=1001

print(sys.getrecursionlimit())

sys.setrecursionlimit(x)

print(sys.getrecursionlimit())

#1-> 1000

#2-> 1001

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

16. 檢查一個對象的內存使用

在 Python 2.7 中,一個 32 比特的整數佔用 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

17. 使用 __slots__ 來減少內存開支

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

import sys

classFileSystem(object):

def __init__(self,files,folders,devices):

self.files= files

self.folders= folders

self.devices= devices

print(sys.getsizeof(FileSystem))

classFileSystem1(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__ 主要是用以限定對象的屬性信息,另外,當生成對象很多時花銷可能會小一些,具體可以參見 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 sys

lprint=lambda *args:sys.stdout.write(” “.join(map(str,args)))

lprint(“python”,”tips”,1000,1001)

#-> python tips 1000 1001

19.從兩個相關的序列構建一個字典

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. 不使用循環構造一個列表

import itertools

test= [[-1,-2],[30,40],[25,35]]

print(list(itertools.chain.from_iterable(test)))

#-> [-1, -2, 30, 40, 25, 35]

22. 在 Python 中實現一個真正的 switch-case 語句

下面的代碼使用一個字典來模擬構造一個 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

轉載自:代碼灣

微信公衆號:



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章