bd@atyun.com
對于所有在編程領域努力工作的人,這里有30個Python最佳實踐、技巧和貼心建議。我相信他們會幫助你輔助你的實際工作,并在這個過程中學到一些有用的東西。
自2020年1月1日起,Python 官方不再支持 Python 2。本文中的很多示例只能在 Python 3 中運行。如果你仍在使用 Python 2.7,請立即升級。
你可以在代碼中檢查 Python 的版本,以確保你的用戶沒有在不兼容的版本中運行腳本。檢查方式如下:
if not sys.version_info > (2, 7): # berate your user for running a 10 year # python version elif not sys.version_info >= (3, 5): # Kindly tell your user (s)he needs to upgrade # because you're using 3.5 features
IPython 本質上就是一個增強版的shell。就沖著自動補齊就值得一試,而且它的功能還不止于此,它還有很多令我愛不釋手的命令,例如:
完整的命令列表,請點擊此處查看(https://ipython.readthedocs.io/en/stable/interactive/magics.html)。
還有一個非常實用的功能:引用上一個命令的輸出。In 和 Out 是實際的對象。你可以通過 Out[3] 的形式使用第三個命令的輸出。
IPython 的安裝命令如下:
pip3 install ipython
你可以利用列表推導式,避免使用循環填充列表時的繁瑣。列表推導式的基本語法如下:
[ expression for item in list if conditional ]
舉一個基本的例子:用一組有序數字填充一個列表:
mylist = [i for i in range(10)] print(mylist) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
由于可以使用表達式,所以你也可以做一些算術運算:
squares = [x**2 for x in range(10)] print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
甚至可以調用外部函數:
def some_function(a): return (a + 5) / 2 my_formula = [some_function(i) for i in range(10)] print(my_formula) # [2, 3, 3, 4, 4, 5, 5, 6, 6, 7]
最后,你還可以使用 ‘if’ 來過濾列表。在如下示例中,我們只保留能被2整除的數字:
filtered = [i for i in range(20) if i%2==0] print(filtered) # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
你可以利用 sys.getsizeof() 來檢查對象使用內存的狀況:
import sys mylist = range(0, 10000) print(sys.getsizeof(mylist)) # 48
等等,為什么這個巨大的列表僅包含48個字節?
因為這里的 range 函數返回了一個類,只不過它的行為就像一個列表。在使用內存方面,range 遠比實際的數字列表更加高效。
你可以試試看使用列表推導式創建一個范圍相同的數字列表:
import sys myreallist = [x for x in range(0, 10000)] print(sys.getsizeof(myreallist)) # 87632
Python 中的函數可以返回一個以上的變量,而且還無需使用字典、列表或類。如下所示:
def get_user(id): # fetch user from database # .... return name, birthdate name, birthdate = get_user(4)
如果返回值的數量有限當然沒問題。但是,如果返回值的數量超過3個,那么你就應該將返回值放入一個(數據)類中。
Python從版本3.7開始提供數據類。與常規類或其他方法(比如返回多個值或字典)相比,數據類有幾個明顯的優勢:
數據類的示例如下:
from dataclasses import dataclass @dataclass class Card: rank: str suit: str card = Card("Q", "hearts") print(card == card) # True print(card.rank) # 'Q' print(card) Card(rank='Q', suit='hearts')
詳細的使用指南請點擊這里(https://realpython.com/python-data-classes/)。
如下的小技巧很巧妙,可以為你節省多行代碼:
a = 1 b = 2 a, b = b, a print (a) # 2 print (b) # 1
從Python 3.5開始,合并字典的操作更加簡單了:
dict1 = { 'a': 1, 'b': 2 } dict2 = { 'b': 3, 'c': 4 } merged = { **dict1, **dict2 } print (merged) # {'a': 1, 'b': 3, 'c': 4}
如果 key 重復,那么第一個字典中的 key 會被覆蓋。
如下技巧真是一個小可愛:
mystring = "10 awesome python tricks" print(mystring.title()) '10 Awesome Python Tricks'
你可以將字符串分割成一個字符串列表。在如下示例中,我們利用空格分割各個單詞:
mystring = "The quick brown fox" mylist = mystring.split(' ') print(mylist) # ['The', 'quick', 'brown', 'fox']
與上述技巧相反,我們可以根據字符串列表創建字符串,然后在各個單詞之間加入空格:
mylist = ['The', 'quick', 'brown', 'fox'] mystring = " ".join(mylist) print(mystring) # 'The quick brown fox'
你可能會問為什么不是 mylist.join(” “),這是個好問題!
根本原因在于,函數 String.join() 不僅可以聯接列表,而且還可以聯接任何可迭代對象。將其放在String中是為了避免在多個地方重復實現同一個功能。
有些人非常喜歡表情符,而有些人則深惡痛絕。我在此鄭重聲明:在分析社交媒體數據時,表情符可以派上大用場。
首先,我們來安裝表情符模塊:
pip3 install 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:'
更多有關表情符的示例和文檔,請點擊此處(https://pypi.org/project/emoji/)。
列表切片的基本語法如下:
a[start:stop:step]
start、stop 和 step 都是可選項。如果不指定,則會使用如下默認值:
示例如下:
# 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'
你可以利用如上切片的方法來反轉字符串或列表。只需指定 step 為 -1,就可以反轉其中的元素:
revstring = "abcdefg"[::-1] print(revstring) # 'gfedcba' revarray = [1, 2, 3, 4, 5][::-1] print(revarray) # [5, 4, 3, 2, 1]
原文鏈接:https://towardsdatascience.com/30-python-best-practices-tips-and-tricks-caefb9f8c5f5
歡迎關注ATYUN官方公眾號
商務合作及內容投稿請聯系郵箱:bd@atyun.com
要發表評論,您必須先登錄。