30個Python優(yōu)秀實踐和技巧,你值得擁有~
1. 使用Python3
溫馨提示:官方宣布自2020年1月一日起將不再支持Python2。這份指南里的大多數(shù)例子也只在Python3中適用。如果您還在使用Python2.7,趕快更新吧。如果您使用的是蘋果電腦,可以使用Homebrew輕松升級。
2. 檢查Python的最低要求版本
您可以直接使用代碼來查看Python版本,確保將來不會出現(xiàn)腳本和Python版本不兼容的情況發(fā)生。請看示例:
- ifnot sys.version_info > (2, 7):
- # berate your user for running a 10 year
- # python version
- elifnot sys.version_info >= (3, 5):
- # Kindly tell your user (s)he needs to upgrade
- # because you're using 3.5 features
viewrawcheck_python_version.py hosted with ❤ by GitHub
3. 使用IPython
作者截圖
實際上,IPython是一個增強的shell。自動完成功能已足以令人驚嘆,但它還有更多功能。我非常喜歡內(nèi)置的魔術(shù)命令。以下是一些例子:
- %cd -用于更改當前工作目錄
- 編輯-打開編輯器,并執(zhí)行您在關(guān)閉編輯器后鍵入的代碼
- %env — 展示當前環(huán)境變量
- %pip install [pkgs] — 在交互環(huán)境下安裝包
- %time 和 %timeit — 計算Python代碼的執(zhí)行時間
另一個有用的功能是引用前一個命令的輸出。In和Out是實際的對象。您可以通過使用Out[3]來進行第三個命令的輸出。
下載Python命令安裝Ipython:
- pip3install ipython
4. 列表推導
列表推導可以替換丑陋的用于填充列表的for循環(huán)。列表推導的基本語法是:
- [expression for item in list if conditional ]
這是一個最基本的例子,使用數(shù)字序列填充列表:
- mylist = [i for i inrange(10)]
- print(mylist)
- # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
viewrawlist_comprehensions_1.py hostedwith ❤ by GitHub
同時你還可以用這種表達進行數(shù)學運算:
- squares = [x**2for x inrange(10)]
- print(squares)
- # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
viewrawlist_comprehensions_2.py hostedwith ❤ by GitHub
甚至額外創(chuàng)建一個新函數(shù):
- defsome_function(a):
- return (a +5) /2
- my_formula = [some_function(i) for i inrange(10)]
- print(my_formula)
- # [2, 3, 3, 4, 4, 5, 5, 6, 6, 7]
viewrawlist_comprehensions_3.py hostedwith ❤ by GitHub
最終,你可以使用“if”來過濾列表。在這個例子中,只保留了能被2整除的值
- filtered = [i for i inrange(20) if i%2==0]
- print(filtered)
- # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
viewrawlist_comprehensions_4.py hosted with ❤ by GitHub
5.檢查對象的內(nèi)存使用
使用 sys.getsizeof(),可以檢查對象的記憶內(nèi)存:
- import sys
- mylist =range(0, 10000)
- print(sys.getsizeof(mylist))
- # 48
viewrawcheck_memory_usage_1.py hostedwith ❤ by GitHub
為什么這樣一個巨大的列表僅占48字節(jié)內(nèi)存? 這是因為range函數(shù)返回的類只表現(xiàn)為一個列表。范圍比使用實際的數(shù)字列表更節(jié)省內(nèi)存。 你可以自己使用列表推導創(chuàng)建同一范圍內(nèi)的實際數(shù)字列表:
- import sys
- myreallist = [x for x inrange(0, 10000)]
- print(sys.getsizeof(myreallist))
- # 87632
viewrawcheck_memory_usage_2.py hosted with ❤ by GitHub
6. 返回多個值
Python中的函數(shù)可以返回多個變量,而無需字典、列表或類。它的工作原理如下:
- defget_user(id):
- # fetch user from database
- # ....
- return name, birthdate
- name, birthdate = get_user(4)
viewrawreturn_multiple_variables.py hosted with ❤ by GitHub
對于有限數(shù)量的返回值,這是可以的。但是任何超過3個值的內(nèi)容都應(yīng)該放到一個(data)類中。
7. 使用數(shù)據(jù)類
從3.7版開始,Python提供了數(shù)據(jù)類。與常規(guī)類或其他替代方法(如返回多個值或字典)相比,有幾個優(yōu)點:
- 一個數(shù)據(jù)類需要最少的代碼
- 可以比較數(shù)據(jù)類,因為已經(jīng)實現(xiàn)了_eq__
- 您以輕易打印一個數(shù)據(jù)類進行調(diào)試,因為也實現(xiàn)了_repr__
- 數(shù)據(jù)類需要類型提示,減少了出錯幾率 下面是一個數(shù)據(jù)類的例子:
- from dataclasses import dataclass
- @dataclass
- classCard:
- rank: str
- suit: str
- card = Card("Q", "hearts")
- print(card == card)
- # True
- print(card.rank)
- # 'Q'
- print(card)
- Card(rank='Q', suit='hearts'
viewrawdataclass.py hosted with ❤ by GitHub
點擊這里查看高階指南 。
8. 變量交換
一個小技巧就可以省略數(shù)行代碼。
- a =1
- b =2
- a, b = b, a
- print (a)
- # 2
- print (b)
- # 1
viewrawin_place_variable_swapping.py hosted with ❤ by GitHub
9. 合并字典(Python3.5+)
自Python3.5 以來,合并字典更為簡便
- dict1 = { 'a': 1, 'b': 2 }
- dict2 = { 'b': 3, 'c': 4 }
- merged = { **dict1, **dict2 }
- print (merged)
- # {'a': 1, 'b': 3, 'c': 4}
viewrawmerging_dicts.py hostedwith ❤ by GitHub
如果有重疊的值,來自第一個字典的值將被覆蓋。
10. 標題大小寫
這只是其中一種有趣的玩法:
- mystring ="10 awesome python tricks"
- print(mystring.title())
- '10 Awesome Python Tricks'
viewrawstring_to_titlecase.py hosted with ❤ by GitHub
11. 切割字符串至列表
可以將字符串拆分為字符串列表。在下例中,根據(jù)空格切割
- mystring ="The quick brown fox"
- mylist = mystring.split(' ')
- print(mylist)
- # ['The', 'quick', 'brown', 'fox']
viewrawstring_to_list.py hosted with ❤ by GitHub
12. 從字符串列表中創(chuàng)建一個字符串
與上一個技巧正好相反,在本例中,從字符串列表中創(chuàng)建一個字符串,并在單詞間輸入空格:
- mylist = ['The', 'quick', 'brown', 'fox']
- mystring =" ".join(mylist)
- print(mystring)
- # 'The quick brown fox'
viewrawlist_to_string.py hostedwith ❤ by GitHub
你或許在想為什么不用mylist.join(" ") ,好問題!
歸根結(jié)底,String.join()函數(shù)不僅可以連接列表,還可以連接任何可迭代的列表。將它放在String中會阻止在多個位置實現(xiàn)相同的功能。
13. 表情
表情要么是歡喜,要么是討厭,這依表情而定。更重要的是,這在分析社交媒體數(shù)據(jù)時尤其有用。 首先,下載表情模塊
- pip3install emoji
下載完之后,就可以按如下操作:
- import emoji
- result = emoji.emojize('Python is :thumbs_up:')
- print(result)
- # 'Python is 👍'
- # You can also reverse this:
- result = emoji.demojize('Python is 👍')
- print(result)
- # 'Python is :thumbs_up:'
viewrawemoji.py hosted with ❤ by GitHub
14. 制作列表切片
列表切片的句法:
- a[start:stop:step]
Start, stop 和 step 都是可選項. 如果未設(shè)置,默認值會是
- Start值為0
- End為字符串末尾
- step值為1
以下是一個例子:
- # We can easily create a new list from
- # the first two elements of a list:
- first_two = [1, 2, 3, 4, 5][0:2]
- print(first_two)
- # [1, 2]
- # And if we use a step value of 2,
- # we can skip over every second number
- # like this:
- steps = [1, 2, 3, 4, 5][0:5:2]
- print(steps)
- # [1, 3, 5]
- # This works on strings too. In Python,
- # you can treat a string like a list of
- # letters:
- mystring ="abcdefdn nimt"[::2]
- print(mystring)
- # 'aced it'
viewrawlist_slicing.py hosted with ❤ by GitHub
15. 反轉(zhuǎn)字符串和列表
使用上面的切片符號來反轉(zhuǎn)字符串或列表。通過使用負的步進值-1,從而反轉(zhuǎn)元素:
- revstring ="abcdefg"[::-1]
- print(revstring)
- # 'gfedcba'
- revarray = [1, 2, 3, 4, 5][::-1]
- print(revarray)
- # [5, 4, 3, 2, 1]
viewrawreversing_stuff.py hosted with ❤ by GitHub
16. 展示小貓
首先,安裝Pillow(Python圖像庫的一個分支):
- pip3install Pillow
下載這張圖片,并把它命名為kittens.jpg:
圖源 TheDigitalArtist Pixabay
可以使用以下代碼來顯示Python代碼中的圖像: 或者直接使用IPython:
- fromPILimport Image
- im = Image.open("kittens.jpg")
- im.show()
- print(im.format, im.size, im.mode)
- # JPEG (1920, 1357) RGB
viewrawpillow.py hosted with ❤ by GitHub

除了顯示圖像,Pillow還可以分析、調(diào)整大小、過濾、增強、變形等等。有關(guān)它的所有特性,請參閱文檔。
17. 使用map()
Python的一個內(nèi)置函數(shù)是map()。map()的語法是: map(function, something_iterable) 給定一個要執(zhí)行的函數(shù),和一些要運行的變量。它可以是任何可迭代的元素。在下面的例子中,我將使用一個列表。
- defupper(s):
- return s.upper()
- mylist =list(map(upper, ['sentence', 'fragment']))
- print(mylist)
- # ['SENTENCE', 'FRAGMENT']
- # Convert a string representation of
- # a number into a list of ints.
- list_of_ints =list(map(int, "1234567")))
- print(list_of_ints)
- # [1, 2, 3, 4, 5, 6, 7]
viewrawmap.py hostedwith ❤ by GitHub
看看自己的代碼,看看是否可以在某處使用map()而不是循環(huán)!
18. 從列表和字符串中提取獨特元素
通過使用set()函數(shù)創(chuàng)建一個集合,可以從一個列表或類似列表的對象中獲得所有獨特的元素:
- mylist = [1, 1, 2, 3, 4, 5, 5, 5, 6, 6]
- print (set(mylist))
- # {1, 2, 3, 4, 5, 6}
- # And since a string can be treated like a
- # list of letters, you can also get the
- # unique letters from a string this way:
- print (set("aaabbbcccdddeeefff"))
- # {'a', 'b', 'c', 'd', 'e', 'f'}
viewrawset.py hosted with ❤ by GitHub
19. 找到頻率出現(xiàn)最高的值
查找列表或字符串中最常出現(xiàn)的值:
- test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4]
- print(max(set(test), key= test.count))
- # 4
viewrawmost_frequent.py hostedwith ❤ by GitHub
你明白為什么會這樣嗎?在繼續(xù)閱讀之前,試著自己找出答案。還沒嘗試嗎?我要告訴你答案了。
- max()將返回列表中的最大值。key參數(shù)接受單個參數(shù)函數(shù)來定制排序順序,在本例中,它是test.count。該函數(shù)應(yīng)用于iterable上的每個項目。
- 測試。count是一個內(nèi)置的列表函數(shù)。它接受一個參數(shù),并將計算該參數(shù)的出現(xiàn)次數(shù)。因此test.count(1)將返回2,而test.count(4)將返回4。
- set(test)返回test中所有的唯一值,因此{1,2,3,4} 因此,我們在這一行代碼中所做的就是獲取test的所有唯一值,即{1,2,3,4}。接下來,max將應(yīng)用list.count 函數(shù),并返回最大值。
20. 創(chuàng)建一個進度條
創(chuàng)建自己的進度條,這很有趣。但是使用進度包更快:
- pip3install progress
現(xiàn)在可以花費更少的時間創(chuàng)建進度條
- from progress.bar import Bar
- bar = Bar('Processing', max=20)
- for i inrange(20):
- # Do some work
- bar.next()
- bar.finish()
viewrawprogress_bar.py hostedwith ❤ by GitHub
21. 在交互式窗口中使用_
可以用下劃線運算符得到最后一個表達式的結(jié)果,例如,在IPython中,如下所示:
- In [1]:3 * 3
- Out[1]: 9In [2]: _ + 3
- Out[2]: 12
這也適用于Pythonshell。此外,IPython shell允許使用Out[n]來獲取[n]中的表達式的值。例如,Out[1]會給出數(shù)字9。
22. 快速創(chuàng)建一個web服務(wù)器
快速啟動web服務(wù)器,提供當前目錄的內(nèi)容:
- python3-m http.server
如果您想與同事共享一些內(nèi)容,或者想測試一個簡單的HTML站點,這是非常有用的。
23. 多行字符串
盡管可以在代碼中使用三引號將多行字符串包括在內(nèi),但這并不理想。放在三引號之間的所有內(nèi)容都將成為字符串,包括格式,如下所示。
我更喜歡第二種方法,該方法將多行連接在一起,使您可以很好地格式化代碼。唯一的缺點是您需要顯式添加換行符。
- s1 ="""Multi line strings can be put
- between triple quotes. It's not ideal
- when formatting your code though"""
- print (s1)
- # Multi line strings can be put
- # between triple quotes. It's not ideal
- # when formatting your code though
- s2 = ("You can also concatenate multiple\n"+
- "strings this way, but you'll have to\n"
- "explicitly put in the newlines")
- print(s2)
- # You can also concatenate multiple
- # strings this way, but you'll have to
- # explicitly put in the newlines
viewrawmultiline_strings.py hosted with ❤ by GitHub
24.三元運算符,用于條件賦值
這是使代碼兼具簡潔性與可讀性的另一種方法:[on_true] if [expression] else[on_false] 例子:
- x = "Success!" if (y== 2) else "Failed!"
25. 計算頻率
使用集合庫中的Counter來獲取包含列表中所有唯一元素計數(shù)的字典:
- from collections import Counter
- mylist = [1, 1, 2, 3, 4, 5, 5, 5, 6, 6]
- c = Counter(mylist)
- print(c)
- # Counter({1: 2, 2: 1, 3: 1, 4: 1, 5: 3, 6: 2})
- # And it works on strings too:
- print(Counter("aaaaabbbbbccccc"))
- # Counter({'a': 5, 'b': 5, 'c': 5})
viewrawcounter.py hosted with ❤ by GitHub
26. 鏈接比較運算符
在Python中鏈接比較運算符,以創(chuàng)建更易讀和簡潔的代碼:
- x =10
- # Instead of:
- if x >5and x <15:
- print("Yes")
- # yes
- # You can also write:
- if5< x <15:
- print("Yes")
- # Yes
viewrawchaining_comparisons.py hosted with ❤ by GitHub
27. 添加一些顏色
使用Colorama,在終端添加點顏色.
- from colorama import Fore, Back, Style
- print(Fore.RED+'some red text')
- print(Back.GREEN+'and with a green background')
- print(Style.DIM+'and in dim text')
- print(Style.RESET_ALL)
- print('back to normal now')
viewrawcolorama.py hosted with ❤ by GitHub
28. 添加日期
python-dateutil模塊提供了對標準datetime模塊的強大擴展。 通過以下方式安裝:
- pip3 install python-dateutil
您可以使用此庫做很多很棒的事情。我只會重點介紹對我來說特別有用的例子:如模糊分析日志文件中的日期等。
- from dateutil.parser import parse
- logline ='INFO 2020-01-01T00:00:01 Happy new year, human.'
- timestamp = parse(log_line, fuzzy=True)
- print(timestamp)
- # 2020-01-01 00:00:01
viewrawdateutil.py hosted with ❤ by GitHub
只需記?。撼R?guī)的Python日期時間功能不奏效時,python-dateutil就派上用場了!
29. 整數(shù)除法
在Python 2中,除法運算符(/)默認為整數(shù)除法,除非操作數(shù)之一是浮點數(shù)。因此,有以下操作:
- # Python 2
- 5 / 2 = 2
- 5 / 2.0 = 2.5
在Python 3中,除法運算符默認為浮點除法,并且//運算符已成為整數(shù)除法。這樣我們得到:
- Python 3
- 5 / 2 = 2.5
- 5 // 2 = 2
30. 使用chardet進行字符集檢測
使用chardet模塊來檢測文件的字符集。在分析大量隨機文本時,這很有用。
安裝方式:
- pip install chardet
現(xiàn)在,有了一個名為chardetect的額外命令行工具,可以像這樣使用:
- chardetect somefile.txt
- somefile.txt: ascii with confidence 1.0
以上就是2020年30條優(yōu)秀的代碼技巧。我希望您能像享受創(chuàng)建列表一樣,享受這些內(nèi)容。