福利!有這30個技巧,應用Python更輕鬆

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

26分鐘


1. 使用Python3


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


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


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


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。自動完成功能已足以令人驚歎,但它還有更多功能。我非常喜歡內置的魔術命令。以下是一些例子:


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

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

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

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

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


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


下載Python命令安裝Ipython:


pip3install ipython


4. 列表推導


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


[expression for item in list if conditional ]


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


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

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

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

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


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.檢查對象的內存使用


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


import sys
mylist =range(0, 10000)
print(sys.getsizeof(mylist))
# 48

viewrawcheck_memory_usage_1.py hostedwith ❤ by GitHub

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


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


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


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中的函數可以返回多個變量,而無需字典、列表或類。它的工作原理如下:


defget_user(id):
# fetch user from database
# ....
return name, birthdate
name, birthdate = get_user(4)

viewrawreturn_multiple_variables.py hosted with ❤ by GitHub

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


7. 使用數據類


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


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

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

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

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


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


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. 變量交換


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

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. 切割字符串至列表



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


mystring ="The quick brown fox"
mylist = mystring.split(' ')
print(mylist)
# ['The', 'quick', 'brown', 'fox']

viewrawstring_to_list.py hosted with ❤ by GitHub

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


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

mylist = ['The', 'quick', 'brown', 'fox']
mystring =" ".join(mylist)
print(mystring)
# 'The quick brown fox'

viewrawlist_to_string.py hostedwith ❤ by GitHub

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


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


13. 表情


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


首先,下載表情模塊

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 都是可選項. 如果未設置,默認值會是


· 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. 反轉字符串和列表


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


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還可以分析、調整大小、過濾、增強、變形等等。有關它的所有特性,請參閱文檔。


17. 使用map()


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


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


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()而不是循環!


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


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


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. 找到頻率出現最高的值


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

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

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


· 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. 創建一個進度條


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


pip3install progress


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


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. 在交互式窗口中使用_



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


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


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


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


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


python3-m http.server

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


23. 多行字符串


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

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


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來獲取包含列表中所有唯一元素計數的字典:


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中鏈接比較運算符,以創建更易讀和簡潔的代碼:


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. 添加一些顏色


截圖 Jonathan Hartley 源Colorama


使用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

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


29. 整數除法


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


# Python 25 / 2 = 25 / 2.0 = 2.5

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

Python 35 / 2 = 2.55 // 2 = 2


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



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


安裝方式:


pip install chardet


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


chardetect somefile.txtsomefile.txt: ascii with confidence 1.0

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



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