30個Python最佳實踐和技巧,你值得擁有

全文共8869字,預計學習時長

26分鐘

30個Python最佳實踐和技巧,你值得擁有


1. 使用Python3


溫馨提示:官方宣佈自2020年1月一日起將不再支持Python2。這份指南里的大多數例子也只在Python3中適用。如果您還在使用Python2.7,趕快更新吧。如果您使用的是蘋果電腦,可以使用Homebrew輕鬆升級。


2. 檢查Python的最低要求版本


您可以直接使用代碼來查看Python版本,確保將來不會出現腳本和Python版本不兼容的情況發生。請看示例:


  1. ifnot sys.version_info > (2, 7):

  2. # berate your user for running a 10 year

  3. # python version

  4. elifnot sys.version_info >= (3, 5):

  5. # Kindly tell your user (s)he needs to upgrade

  6. # because you're using 3.5 features

viewrawcheck_python_version.py hosted with ❤ by GitHub

3. 使用IPython


30個Python最佳實踐和技巧,你值得擁有

作者截圖


實際上,IPython是一個增強的shell。自動完成功能已足以令人驚歎,但它還有更多功能。我非常喜歡內置的魔術命令。以下是一些例子:


· %cd -用於更改當前工作目錄

· 編輯-打開編輯器,並執行您在關閉編輯器後鍵入的代碼

· %env — 展示當前環境變量

· %pip install [pkgs] — 在交互環境下安裝包

· %time 和 %timeit — 計算Python代碼的執行時間


另一個有用的功能是引用前一個命令的輸出。In和Out是實際的對象。您可以通過使用Out[3]來進行第三個命令的輸出。


下載Python命令安裝Ipython:


  1. pip3install ipython


4. 列表推導


列表推導可以替換醜陋的用於填充列表的for循環。列表推導的基本語法是:


  1. [expression for item in list if conditional ]


這是一個最基本的例子,使用數字序列填充列表:


  1. mylist = [i for i inrange(10)]

  2. print(mylist)

  3. # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

viewrawlist_comprehensions_1.py hostedwith ❤ by GitHub

同時你還可以用這種表達進行數學運算:

  1. squares = [x**2for x inrange(10)]

  2. print(squares)

  3. # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

viewrawlist_comprehensions_2.py hostedwith ❤ by GitHub

甚至額外創建一個新函數:


  1. defsome_function(a):

  2. return (a +5) /2

  3. my_formula = [some_function(i) for i inrange(10)]

  4. print(my_formula)

  5. # [2, 3, 3, 4, 4, 5, 5, 6, 6, 7]

viewrawlist_comprehensions_3.py hostedwith ❤ by GitHub

最終,你可以使用“if”來過濾列表。在這個例子中,只保留了能被2整除的值


  1. filtered = [i for i inrange(20) if i%2==0]

  2. print(filtered)

  3. # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

viewrawlist_comprehensions_4.py hosted with ❤ by GitHub

5.檢查對象的內存使用


使用 sys.getsizeof(),可以檢查對象的記憶內存:


  1. import sys

  2. mylist =range(0, 10000)

  3. print(sys.getsizeof(mylist))

  4. # 48

viewrawcheck_memory_usage_1.py hostedwith ❤ by GitHub

為什麼這樣一個巨大的列表僅佔48字節內存?


這是因為range函數返回的類只表現為一個列表。範圍比使用實際的數字列表更節省內存。


你可以自己使用列表推導創建同一範圍內的實際數字列表:


  1. import sys

  2. myreallist = [x for x inrange(0, 10000)]

  3. print(sys.getsizeof(myreallist))

  4. # 87632

viewrawcheck_memory_usage_2.py hosted with ❤ by GitHub

6. 返回多個值


30個Python最佳實踐和技巧,你值得擁有


Python中的函數可以返回多個變量,而無需字典、列表或類。它的工作原理如下:


  1. defget_user(id):

  2. # fetch user from database

  3. # ....

  4. return name, birthdate

  5. name, birthdate = get_user(4)

viewrawreturn_multiple_variables.py hosted with ❤ by GitHub

對於有限數量的返回值,這是可以的。但是任何超過3個值的內容都應該放到一個(data)類中。


7. 使用數據類


從3.7版開始,Python提供了數據類。與常規類或其他替代方法(如返回多個值或字典)相比,有幾個優點:


· 一個數據類需要最少的代碼

· 可以比較數據類,因為已經實現了_eq__

· 您以輕易打印一個數據類進行調試,因為也實現了_repr__

· 數據類需要類型提示,減少了出錯幾率


下面是一個數據類的例子:


  1. from dataclasses import dataclass

  2. @dataclass

  3. classCard:

  4. rank: str

  5. suit: str

  6. card = Card("Q", "hearts")

  7. print(card == card)

  8. # True

  9. print(card.rank)

  10. # 'Q'

  11. print(card)

  12. Card(rank='Q', suit='hearts'

viewrawdataclass.py hosted with ❤ by GitHub

點擊這裡查看高階指南 。


8. 變量交換


一個小技巧就可以省略數行代碼。

  1. a =1

  2. b =2

  3. a, b = b, a

  4. print (a)

  5. # 2

  6. print (b)

  7. # 1

viewrawin_place_variable_swapping.py hosted with ❤ by GitHub

9. 合併字典(Python3.5+)


自Python3.5 以來,合併字典更為簡便


  1. dict1 = { 'a': 1, 'b': 2 }

  2. dict2 = { 'b': 3, 'c': 4 }

  3. merged = { **dict1, **dict2 }

  4. print (merged)

  5. # {'a': 1, 'b': 3, 'c': 4}

viewrawmerging_dicts.py hostedwith ❤ by GitHub

如果有重疊的值,來自第一個字典的值將被覆蓋。


10. 標題大小寫


這只是其中一種有趣的玩法:

  1. mystring ="10 awesome python tricks"

  2. print(mystring.title())

  3. '10 Awesome Python Tricks'

viewrawstring_to_titlecase.py hosted with ❤ by GitHub

11. 切割字符串至列表


30個Python最佳實踐和技巧,你值得擁有


可以將字符串拆分為字符串列表。在下例中,根據空格切割


  1. mystring ="The quick brown fox"

  2. mylist = mystring.split(' ')

  3. print(mylist)

  4. # ['The', 'quick', 'brown', 'fox']

viewrawstring_to_list.py hosted with ❤ by GitHub

12. 從字符串列表中創建一個字符串


與上一個技巧正好相反,在本例中,從字符串列表中創建一個字符串,並在單詞間輸入空格:

  1. mylist = ['The', 'quick', 'brown', 'fox']

  2. mystring =" ".join(mylist)

  3. print(mystring)

  4. # 'The quick brown fox'

viewrawlist_to_string.py hostedwith ❤ by GitHub

你或許在想為什麼不用mylist.join(" ") ,好問題!


歸根結底,String.join()函數不僅可以連接列表,還可以連接任何可迭代的列表。將它放在String中會阻止在多個位置實現相同的功能。


13. 表情


表情要麼是歡喜,要麼是討厭,這依表情而定。更重要的是,這在分析社交媒體數據時尤其有用。


首先,下載表情模塊

  1. pip3install emoji


下載完之後,就可以按如下操作:


  1. import emoji

  2. result = emoji.emojize('Python is :thumbs_up:')

  3. print(result)

  4. # 'Python is '

  5. # You can also reverse this:

  6. result = emoji.demojize('Python is ')

  7. print(result)

  8. # 'Python is :thumbs_up:'

viewrawemoji.py hosted with ❤ by GitHub

30個Python最佳實踐和技巧,你值得擁有

訪問表情包頁面查看更多描述和示例


14. 製作列表切片


列表切片的句法:


  1. a[start:stop:step]


Start, stop 和 step 都是可選項. 如果未設置,默認值會是


· Start值為0

· End為字符串末尾

· step值為1


以下是一個例子:


  1. # We can easily create a new list from

  2. # the first two elements of a list:

  3. first_two = [1, 2, 3, 4, 5][0:2]

  4. print(first_two)

  5. # [1, 2]

  6. # And if we use a step value of 2,

  7. # we can skip over every second number

  8. # like this:

  9. steps = [1, 2, 3, 4, 5][0:5:2]

  10. print(steps)

  11. # [1, 3, 5]

  12. # This works on strings too. In Python,

  13. # you can treat a string like a list of

  14. # letters:

  15. mystring ="abcdefdn nimt"[::2]

  16. print(mystring)

  17. # 'aced it'

viewrawlist_slicing.py hosted with ❤ by GitHub

15. 反轉字符串和列表


使用上面的切片符號來反轉字符串或列表。通過使用負的步進值-1,從而反轉元素:


  1. revstring ="abcdefg"[::-1]

  2. print(revstring)

  3. # 'gfedcba'

  4. revarray = [1, 2, 3, 4, 5][::-1]

  5. print(revarray)

  6. # [5, 4, 3, 2, 1]

viewrawreversing_stuff.py hosted with ❤ by GitHub

16. 展示小貓


首先,安裝Pillow(Python圖像庫的一個分支):


  1. pip3install Pillow

下載這張圖片,並把它命名為kittens.jpg:

30個Python最佳實踐和技巧,你值得擁有

圖源 TheDigitalArtist Pixabay


可以使用以下代碼來顯示Python代碼中的圖像:


或者直接使用IPython:


  1. fromPILimport Image

  2. im = Image.open("kittens.jpg")

  3. im.show()

  4. print(im.format, im.size, im.mode)

  5. # JPEG (1920, 1357) RGB

viewrawpillow.py hosted with ❤ by GitHub

30個Python最佳實踐和技巧,你值得擁有


除了顯示圖像,Pillow還可以分析、調整大小、過濾、增強、變形等等。有關它的所有特性,請參閱文檔。


17. 使用map()


Python的一個內置函數是map()。map()的語法是: map(function, something_iterable)


給定一個要執行的函數,和一些要運行的變量。它可以是任何可迭代的元素。在下面的例子中,我將使用一個列表。


  1. defupper(s):

  2. return s.upper()

  3. mylist =list(map(upper, ['sentence', 'fragment']))

  4. print(mylist)

  5. # ['SENTENCE', 'FRAGMENT']

  6. # Convert a string representation of

  7. # a number into a list of ints.

  8. list_of_ints =list(map(int, "1234567")))

  9. print(list_of_ints)

  10. # [1, 2, 3, 4, 5, 6, 7]

viewrawmap.py hostedwith ❤ by GitHub

看看自己的代碼,看看是否可以在某處使用map()而不是循環!


18. 從列表和字符串中提取獨特元素


通過使用set()函數創建一個集合,可以從一個列表或類似列表的對象中獲得所有獨特的元素:


  1. mylist = [1, 1, 2, 3, 4, 5, 5, 5, 6, 6]

  2. print (set(mylist))

  3. # {1, 2, 3, 4, 5, 6}

  4. # And since a string can be treated like a

  5. # list of letters, you can also get the

  6. # unique letters from a string this way:

  7. print (set("aaabbbcccdddeeefff"))

  8. # {'a', 'b', 'c', 'd', 'e', 'f'}

viewrawset.py hosted with ❤ by GitHub

19. 找到頻率出現最高的值


查找列表或字符串中最常出現的值:

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

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

  3. # 4

viewrawmost_frequent.py hostedwith ❤ by GitHub

你明白為什麼會這樣嗎?在繼續閱讀之前,試著自己找出答案。還沒嘗試嗎?我要告訴你答案了。


· max()將返回列表中的最大值。key參數接受單個參數函數來定製排序順序,在本例中,它是test.count。該函數應用於iterable上的每個項目。

· 測試。count是一個內置的列表函數。它接受一個參數,並將計算該參數的出現次數。因此test.count(1)將返回2,而test.count(4)將返回4。

· set(test)返回test中所有的唯一值,因此{1,2,3,4}


因此,我們在這一行代碼中所做的就是獲取test的所有唯一值,即{1,2,3,4}。接下來,max將應用list.count 函數,並返回最大值。


20. 創建一個進度條


創建自己的進度條,這很有趣。但是使用進度包更快:


  1. pip3install progress


現在可以花費更少的時間創建進度條


  1. from progress.bar import Bar

  2. bar = Bar('Processing', max=20)

  3. for i inrange(20):

  4. # Do some work

  5. bar.next()

  6. bar.finish()

viewrawprogress_bar.py hostedwith ❤ by GitHub


21. 在交互式窗口中使用_


30個Python最佳實踐和技巧,你值得擁有


可以用下劃線運算符得到最後一個表達式的結果,例如,在IPython中,如下所示:


  1. In [1]:3 * 3
  2. Out[1]: 9In [2]: _ + 3
  3. Out[2]: 12


這也適用於Pythonshell。此外,IPython shell允許使用Out[n]來獲取[n]中的表達式的值。例如,Out[1]會給出數字9。


22. 快速創建一個web服務器


快速啟動web服務器,提供當前目錄的內容:


  1. python3-m http.server

如果您想與同事共享一些內容,或者想測試一個簡單的HTML站點,這是非常有用的。


23. 多行字符串


儘管可以在代碼中使用三引號將多行字符串包括在內,但這並不理想。放在三引號之間的所有內容都將成為字符串,包括格式,如下所示。

我更喜歡第二種方法,該方法將多行連接在一起,使您可以很好地格式化代碼。唯一的缺點是您需要顯式添加換行符。


  1. s1 ="""Multi line strings can be put

  2. between triple quotes. It's not ideal

  3. when formatting your code though"""

  4. print (s1)

  5. # Multi line strings can be put

  6. # between triple quotes. It's not ideal

  7. # when formatting your code though

  8. s2 = ("You can also concatenate multiple\\n"+

  9. "strings this way, but you'll have to\\n"

  10. "explicitly put in the newlines")

  11. print(s2)

  12. # You can also concatenate multiple

  13. # strings this way, but you'll have to

  14. # explicitly put in the newlines

viewrawmultiline_strings.py hosted with ❤ by GitHub

24.三元運算符,用於條件賦值


這是使代碼兼具簡潔性與可讀性的另一種方法:[on_true] if [expression] else[on_false]


例子:


  1. x = "Success!" if (y== 2) else "Failed!"


25. 計算頻率


使用集合庫中的Counter來獲取包含列表中所有唯一元素計數的字典:


  1. from collections import Counter

  2. mylist = [1, 1, 2, 3, 4, 5, 5, 5, 6, 6]

  3. c = Counter(mylist)

  4. print(c)

  5. # Counter({1: 2, 2: 1, 3: 1, 4: 1, 5: 3, 6: 2})

  6. # And it works on strings too:

  7. print(Counter("aaaaabbbbbccccc"))

  8. # Counter({'a': 5, 'b': 5, 'c': 5})

viewrawcounter.py hosted with ❤ by GitHub

26. 鏈接比較運算符


在Python中鏈接比較運算符,以創建更易讀和簡潔的代碼:


  1. x =10

  2. # Instead of:

  3. if x >5and x <15:

  4. print("Yes")

  5. # yes

  6. # You can also write:

  7. if5< x <15:

  8. print("Yes")

  9. # Yes

viewrawchaining_comparisons.py hosted with ❤ by GitHub

27. 添加一些顏色


30個Python最佳實踐和技巧,你值得擁有

截圖 Jonathan Hartley 源Colorama


使用Colorama,在終端添加點顏色.


  1. from colorama import Fore, Back, Style

  2. print(Fore.RED+'some red text')

  3. print(Back.GREEN+'and with a green background')

  4. print(Style.DIM+'and in dim text')

  5. print(Style.RESET_ALL)

  6. print('back to normal now')

viewrawcolorama.py hosted with ❤ by GitHub

28. 添加日期


python-dateutil模塊提供了對標準datetime模塊的強大擴展。 通過以下方式安裝:

  1. pip3 install python-dateutil


您可以使用此庫做很多很棒的事情。我只會重點介紹對我來說特別有用的例子:如模糊分析日誌文件中的日期等。


  1. from dateutil.parser import parse

  2. logline ='INFO 2020-01-01T00:00:01 Happy new year, human.'

  3. timestamp = parse(log_line, fuzzy=True)

  4. print(timestamp)

  5. # 2020-01-01 00:00:01

viewrawdateutil.py hosted with ❤ by GitHub

只需記住:常規的Python日期時間功能不奏效時,python-dateutil就派上用場了!


29. 整數除法


在Python 2中,除法運算符(/)默認為整數除法,除非操作數之一是浮點數。因此,有以下操作:


  1. # Python 2
  2. 5 / 2 = 2
  3. 5 / 2.0 = 2.5

在Python 3中,除法運算符默認為浮點除法,並且//運算符已成為整數除法。這樣我們得到:

  1. Python 3
  2. 5 / 2 = 2.5
  3. 5 // 2 = 2


30. 使用chardet進行字符集檢測


30個Python最佳實踐和技巧,你值得擁有


使用chardet模塊來檢測文件的字符集。在分析大量隨機文本時,這很有用。


安裝方式:


  1. pip install chardet


現在,有了一個名為chardetect的額外命令行工具,可以像這樣使用:


  1. chardetect somefile.txt
  2. somefile.txt: ascii with confidence 1.0

以上就是2020年30條最佳的代碼技巧。我希望您能像享受創建列表一樣,享受這些內容。如果您有任何意見,請隨時發表評論!


30個Python最佳實踐和技巧,你值得擁有


30個Python最佳實踐和技巧,你值得擁有

我們一起分享AI學習與發展的乾貨


分享到:


相關文章: