Python程序員需要知道的30個技巧

1  直接交換兩個數字位置

1x, y = 10, 202print(x, y)3x, y = y, x4print(x, y)5#1 (10, 20)6#2 (20, 10)

2  比較運算符的鏈接

1n = 102result = 1 < n < 203print(result)4# True5result = 1 > n <= 96print(result)7# False

3  在條件語句中使用三元運算符

1 [on_true]if[expression]else[on_false]

這樣可以使你的代碼緊湊和簡明。

1x = 10if(y == 9)else20

同時,我們也可以在類對象中使用。

1x = (classAify == 1elseclassB)(param1, param2)

在上面的例子中,有兩個類分別是類A和類B,其中一個類的構造函數將會被訪問。下面的例子加入了評估最小數的條件。

1def small(a, b, c): 2returnaifa <= banda <= celse(bifb <= aandb <= celse c) 3 4print(small(1, 0, 1)) 5print(small(1, 2, 2)) 6print(small(2, 2, 3)) 7print(small(5, 4, 3)) 8 9#Output10#0 #1 #2 #3

我們甚至可以在一個列表生成器中使用三元運算符。

1[m**2ifm > 10elsem**4forminrange(50)]23#=> [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  多行字符串

使用反斜槓(backslashes)的基本方法最初來源於c語言,當然,我們熟悉的方法是使用三個引號(triple-quotes)

1multiStr ="select * from multi_row \2where row_id < 5"3print(multiStr)45#select * from multi_row where row_id < 5

這樣做的問題就是沒有適當的縮進,如果縮進的話將會使空格也包含在字符串中,所以最終的解決方案就是把字符串分割成多行,把每行字符串放在引號中,然後將它們放在中括號中,如下:

1multiStr= ("select * from multi_row "2"where row_id < 5 "3"order by age")4print(multiStr)

5# select * from multi_row where row_id < 5 order by age

5  在列表中存儲變量

我們可以只用列表來初始化多個變量,拆開列表時,變量的數不應超過列表中元素的個數。

1testList = [1,2,3]2x, y, z = testList34print(x, y, z)56#-> 1 2 3

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

1import threading 2import socket34print(threading)5print(socket)67#1- <module 'threading' from '/usr/lib/python2.7/threading.py'>8#2- <module 'socket' from '/usr/lib/python2.7/socket.py'>

7  python的IDLE的交互式功能“_”

1>>> 2 + 1233>>> _435>>>print _63

_下劃線輸出上次打印的結果

在學習中有迷茫不知如何學習的朋友小編推薦一個學Python的學習q u n 227  -435-  450可以來了解一起進步一起學習!免費分享視頻資料

8  字典/集合生成器

1testDict = {i: i * iforiinxrange(10)} 2testSet = {i * 2foriinxrange(10)}34print(testSet)5print(testDict)67#set([0, 2, 4, 6, 8, 10, 12, 14, 16, 18])8#{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

9  調試腳本

我們可以使用pdb模塊來爲我們的腳本設置斷點。

1import pdb2pdb.set_trace()

10  設置文件共享

Python允許你啓動一個HTTP服務,你可以在服務的根目錄中共享文件。

1# PYTHON 22python -m SimpleHTTPServer3# PYTHON 34python3 -m http.server

服務將啓動默認的8000端口,你也可以在上面的命令中最後加上一個參數來自定義端口。

11  在Python中檢查對象

簡單的說就是使用dir()方法,用這個方法來查看這個對象的所有方法。

1test = [1, 3, 5, 7]2print( dir(test) )3['__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條件語句

爲了驗證多個值,我們可以試試一下方法:

1使用2ifmin[1,3,5,7]:3而不是4ifm==1orm==3orm==5orm==7:

作爲選擇,我們可以在‘in’運算符後面使用‘{1,3,5,7}’代替‘[1,3,5,7]’因爲 ‘set’ can access each element by O(1)。

13  在運行時檢測Python版本

1import sys 2 3#Detect the Python version currently in use. 4ifnothasattr(sys,"hexversion")orsys.hexversion != 50660080: 5print("Sorry, you aren't running on Python 3.5\n") 6print("Please upgrade to 3.5.\n") 7sys.exit(1) 8 9#Print Python version in a readable format.10print("Current Python version: ", sys.version)

上面的代碼中,你可以使用sys.version_info >= (3, 5)來代替sys.hexversion != 50660080。

當運行在Python2.7中時:

1Python 2.7.10 (default, Jul 14 2015, 19:46:27)2[GCC 4.8.2] on linux34Sorry, you aren't running on Python 3.556Please upgrade to 3.5.

當運行在Python3.5上時:

1Python 3.5.1 (default, Dec 2015, 13:05:11)2[GCC 4.8.2] on linux34Current Python version:  3.5.2 (default, Aug 22 2016, 21:11:05) 5[GCC 5.3.0]

14 結合多個字符串

1test = ['I','Like','Python','automation']2print''.join(test)

15  萬能的逆轉機制

#逆轉列表testList = [1, 3, 5]

testList.reverse()print(testList)

#-> [5, 3, 1]#在一個循環中反向迭代forelementinreversed([1,3,5]):print(element)

#1-> 5#2-> 3#3-> 1#字符串"Test Python"[::-1]#使用切片反向列表[1, 3, 5][::-1]

16  枚舉器

1testlist = [10, 20, 30]2fori, valuein enumerate(testlist):3print(i,': ', value)45#1-> 0 : 106#2-> 1 : 207#3-> 2 : 30

17  使用枚舉

1class Shapes: 2Circle, Square, Triangle, Quadrangle = range(4) 3 4print(Shapes.Circle) 5print(Shapes.Square) 6print(Shapes.Triangle) 7print(Shapes.Quadrangle) 8 9#1-> 010#2-> 111#3-> 212#4-> 3

18  從函數中返回多個值

1# function returning multiple values. 2def x(): 3return1, 2, 3, 4 4 5# Calling the above function. 6a, b, c, d = x() 7 8print(a, b, c, d) 910#-> 1 2 3 4

19  使用星號運算符解包函數參數

1def test(x, y, z): 2print(x, y, z) 3 4testDict = {'x': 1,'y': 2,'z': 3}  5testList = [10, 20, 30] 6 7test(*testDict) 8test(**testDict) 9test(*testList)1011#1-> x y z12#2-> 1 2 313#3-> 10 20 30

20  使用字典來存儲表達式

1stdcalc = { 2'sum':lambdax, y: x + y, 3'subtract':lambdax, y: x - y 4} 5 6print(stdcalc['sum'](9,3)) 7print(stdcalc['subtract'](9,3)) 8 9#1-> 1210#2-> 6

21  在任意一行數字中計算階乘

#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

22  在列表中找到出現次數最多的元素

1test = [1,2,3,4,2,2,3,1,4,4,4]2print(max(set(test), key=test.count))34#-> 4

23  重置遞歸次數限制

1import sys 2 3x=1001 4print(sys.getrecursionlimit()) 5 6sys.setrecursionlimit(x) 7print(sys.getrecursionlimit()) 8 9#1-> 100010#2-> 1001

24  檢查對象的內存使用

1#IN PYTHON 2.7. 2import sys 3x=1 4print(sys.getsizeof(x)) 5 6#-> 24 7 8#IN PYTHON 3.5. 9import sys10x=111print(sys.getsizeof(x))1213#-> 28

25  使用 __slot__ 來減少內存開支

1import sys 2class FileSystem(object): 3 4def__init__(self, files, folders, devices): 5self.files = files 6self.folders = folders 7self.devices = devices 8 9print(sys.getsizeof( FileSystem ))1011class FileSystem1(object):1213__slots__= ['files','folders','devices']1415def__init__(self, files, folders, devices):16self.files = files17self.folders = folders18self.devices = devices1920print(sys.getsizeof( FileSystem1 ))2122#In Python 3.523#1-> 101624#2-> 888

顯然,從結果中可以看到內存使用中有節省。但是你應該用__slots__當一個類的內存開銷過大。只有在分析應用程序後才能做。否則,你會使代碼難以改變,並沒有真正的好處。

26  使用lambda處理打印

1import sys2lprint=lambda*args:sys.stdout.write("".join(map(str,args)))3lprint("python","tips",1000,1001)45#-> python tips 1000 1001

27  通過兩個相關序列創建字典

1t1 = (1, 2, 3)2t2 = (10, 20, 30)34print(dict (zip(t1,t2)))56#-> {1: 10, 2: 20, 3: 30}

28  搜索多個前綴後綴字符串

1print("http://www.google.com".startswith(("http://","https://")))2print("http://www.google.co.uk".endswith((".com",".co.uk")))34#1-> True5#2-> True

29  不使用任何循環形成一個統一的列表

1import itertools2test = [[-1, -2], [30, 40], [25, 35]]3print(list(itertools.chain.from_iterable(test)))45#-> [-1, -2, 30, 40, 25, 35]

30  在Python中實現一個真正的切換實例聲明

1def xswitch(x):  2return xswitch._system_dict.get(x, None)  3 4xswitch._system_dict = {'files': 10,'folders': 5,'devices': 2} 5 6print(xswitch('default')) 7print(xswitch('devices')) 8 9#1-> None10#2-> 2

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