1. 程式人生 > >30個基本的Python技巧和竅門程式設計師你知道麼

30個基本的Python技巧和竅門程式設計師你知道麼

30 tips & tricks for Python Programming

1  直接交換兩個數字位置

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

2  比較運算子的連結

複製程式碼

1 n = 10
2 result = 1 < n < 20
3 print(result)
4 # True
5 result = 1 > n <= 9
6 print(result)
7 # False

複製程式碼

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

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

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

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

同時,我們也可以在類物件中使用。

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

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

複製程式碼

 1 def small(a, b, c):
 2     return a if a <= b and a <= c else (b if b <= a and b <= c else c)
 3     
 4 print(small(1, 0, 1))
 5 print(small(1, 2, 2))
 6 print(small(2, 2, 3))
 7 print(small(5, 4, 3))
 8  
 9 #Output
10 #0 #1 #2 #3

複製程式碼

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

1 [m**2 if m > 10 else m**4 for m in range(50)]
2  
3 #=> [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)

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

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

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

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

5  在列表中儲存變數

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

1 testList = [1,2,3]
2 x, y, z = testList
3  
4 print(x, y, z)
5  
6 #-> 1 2 3

6  列印引入模組的檔案路徑

複製程式碼

1 import threading 
2 import socket
3  
4 print(threading)
5 print(socket)
6  
7 #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 + 1
2 3
3 >>> _
4 3
5 >>> print _
6 3

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

8  字典/集合生成器

複製程式碼

1 testDict = {i: i * i for i in xrange(10)} 
2 testSet = {i * 2 for i in xrange(10)}
3  
4 print(testSet)
5 print(testDict)
6  
7 #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模組來為我們的指令碼設定斷點。

1 import pdb
2 pdb.set_trace()

10  設定檔案共享

Python允許你啟動一個HTTP服務,你可以在服務的根目錄中共享檔案。

1 # PYTHON 2
2 python -m SimpleHTTPServer
3 # PYTHON 3
4 python3 -m http.server

服務將啟動預設的8000埠,你也可以在上面的命令中最後加上一個引數來自定義埠。

11  在Python中檢查物件

簡單的說就是使用dir()方法,用這個方法來檢視這個物件的所有方法。

複製程式碼

1 test = [1, 3, 5, 7]
2 print( 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 使用
2 if m in [1,3,5,7]:
3 而不是
4 if m==1 or m==3 or m==5 or m==7:

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

13  在執行時檢測Python版本

複製程式碼

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

複製程式碼

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

當執行在Python2.7中時:

1 Python 2.7.10 (default, Jul 14 2015, 19:46:27)
2 [GCC 4.8.2] on linux
3    
4 Sorry, you aren't running on Python 3.5
5  
6 Please upgrade to 3.5.

當執行在Python3.5上時:

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

14 結合多個字串

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

15  萬能的逆轉機制

複製程式碼

#逆轉列表
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]

#使用切片反向列表
[1, 3, 5][::-1]

複製程式碼

16  列舉器

複製程式碼

1 testlist = [10, 20, 30]
2 for i, value in enumerate(testlist):
3     print(i, ': ', value)
4  
5 #1-> 0 : 10
6 #2-> 1 : 20
7 #3-> 2 : 30

複製程式碼

17  使用列舉

複製程式碼

 1 class Shapes:
 2     Circle, Square, Triangle, Quadrangle = range(4)
 3  
 4 print(Shapes.Circle)
 5 print(Shapes.Square)
 6 print(Shapes.Triangle)
 7 print(Shapes.Quadrangle)
 8  
 9 #1-> 0
10 #2-> 1
11 #3-> 2
12 #4-> 3

複製程式碼

18  從函式中返回多個值

複製程式碼

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

複製程式碼

19  使用星號運算子解包函式引數

複製程式碼

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

複製程式碼

20  使用字典來儲存表示式

複製程式碼

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

複製程式碼

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

複製程式碼

#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

複製程式碼

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

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

23  重置遞迴次數限制

複製程式碼

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

複製程式碼

24  檢查物件的記憶體使用

複製程式碼

 1 #IN PYTHON 2.7.
 2 import sys
 3 x=1
 4 print(sys.getsizeof(x))
 5  
 6 #-> 24
 7 
 8 #IN PYTHON 3.5.
 9 import sys
10 x=1
11 print(sys.getsizeof(x))
12  
13 #-> 28

複製程式碼

25  使用 __slot__ 來減少記憶體開支

複製程式碼

 1 import sys
 2 class FileSystem(object):
 3  
 4     def __init__(self, files, folders, devices):
 5         self.files = files
 6         self.folders = folders
 7         self.devices = devices
 8  
 9 print(sys.getsizeof( FileSystem ))
10  
11 class FileSystem1(object):
12  
13     __slots__ = ['files', 'folders', 'devices']
14     
15     def __init__(self, files, folders, devices):
16         self.files = files
17         self.folders = folders
18         self.devices = devices
19  
20 print(sys.getsizeof( FileSystem1 ))
21  
22 #In Python 3.5
23 #1-> 1016
24 #2-> 888

複製程式碼

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

26  使用lambda處理列印

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

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

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

28  搜尋多個字首字尾字串

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

29  不使用任何迴圈形成一個統一的列表

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

30  在Python中實現一個真正的切換例項宣告

複製程式碼

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

複製程式碼