bd@atyun.com
我終于找到了一個充分的借口可以在我的文章中顯示貓貓了,哈哈!當然,你也可以利用它來顯示圖片。首先你需要安裝 Pillow,這是一個 Python 圖片庫的分支:
pip3 install Pillow
接下來,你可以將如下圖片下載到一個名叫 kittens.jpg 的文件中:
然后,你就可以通過如下 Python 代碼顯示上面的圖片:
from PIL import Image im = Image.open("kittens.jpg") im.show() print(im.format, im.size, im.mode) # JPEG (1920, 1357) RGB
Pillow 還有很多顯示該圖片之外的功能。它可以分析、調整大小、過濾、增強、變形等等。完整的文檔,請點擊這里(https://pillow.readthedocs.io/en/stable/)。
Python 有一個自帶的函數叫做 map(),語法如下:
map(function, something_iterable)
所以,你需要指定一個函數來執行,或者一些東西來執行。任何可迭代對象都可以。在如下示例中,我指定了一個列表:
def upper(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]
你可以仔細看看自己的代碼,看看能不能用 map() 替代某處的循環。
如果你利用函數 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'}
你可以通過如下方法查找出現頻率最高的值:
test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4] print(max(set(test), key = test.count)) # 4
你能看懂上述代碼嗎?想法搞明白上述代碼再往下讀。
沒看懂?我來告訴你吧:
因此,這一行代碼完成的操作是:首先獲取 test 所有的唯一值,即{1, 2, 3, 4};然后,max 會針對每一個值執行 list.count,并返回最大值。
這一行代碼可不是我個人的發明。
你可以創建自己的進度條,聽起來很有意思。但是,更簡單的方法是使用 progress 包:
pip3 install progress
接下來,你就可以輕松地創建進度條了:
from progress.bar import Bar bar = Bar('Processing', max=20) for i in range(20): # Do some work bar.next() bar.finish()
你可以通過下劃線運算符獲取上一個表達式的結果,例如在 IPython 中,你可以這樣操作:
In [1]: 3 * 3 Out[1]: 9In [2]: _ + 3 Out[2]: 12
Python Shell 中也可以這樣使用。另外,在 IPython shell 中,你還可以通過 Out[n] 獲取表達式 In[n] 的值。例如,在如上示例中,Out[1] 將返回數字9。
你可以快速啟動一個Web服務,并提供當前目錄的內容:
python3 -m http.server
當你想與同事共享某個文件,或測試某個簡單的HTML網站時,就可以考慮這個方法。
雖然你可以用三重引號將代碼中的多行字符串括起來,但是這種做法并不理想。所有放在三重引號之間的內容都會成為字符串,包括代碼的格式,如下所示。
我更喜歡另一種方法,這種方法不僅可以將多行字符串連接在一起,而且還可以保證代碼的整潔。唯一的缺點是你需要明確指定換行符。
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
這種方法可以讓代碼更簡潔,同時又可以保證代碼的可讀性:
[on_true] if [expression] else [on_false]
示例如下:
x = "Success!" if (y == 2) else "Failed!"
你可以使用集合庫中的 Counter 來獲取列表中所有唯一元素的出現次數,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})
你可以在 Python 中將多個比較運算符鏈接到一起,如此就可以創建更易讀、更簡潔的代碼:
x = 10 # Instead of: if x > 5 and x < 15: print("Yes") # yes # You can also write: if 5 < x < 15: print("Yes") # Yes
你可以通過 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')
python-dateutil 模塊作為標準日期模塊的補充,提供了非常強大的擴展,你可以通過如下命令安裝:
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
你只需記?。寒斢龅匠R?Python 日期時間功能無法解決的問題時,就可以考慮 python-dateutil !
在 Python 2 中,除法運算符(/)默認為整數除法,除非其中一個操作數是浮點數。因此,你可以這么寫:
# Python 2 5 / 2 = 2 5 / 2.0 = 2.5
在 Python 3 中,除法運算符(/)默認為浮點除法,而整數除法的運算符為 //。因此,你需要這么寫:
Python 3 5 / 2 = 2.5 5 // 2 = 2
這項變更背后的動機,請參閱 PEP-0238(https://www.python.org/dev/peps/pep-0238/)。
你可以使用 chardet 模塊來檢測文件的字符集。在分析大量隨機文本時,這個模塊十分實用。安裝方法如下:
pip install chardet
安裝完成后,你就可以使用命令行工具 chardetect 了,使用方法如下:
chardetect somefile.txt somefile.txt: ascii with confidence 1.0
你也可以在編程中使用該庫,完整的文檔請點擊這里(https://chardet.readthedocs.io/en/latest/usage.html)。
原文鏈接:https://towardsdatascience.com/30-python-best-practices-tips-and-tricks-caefb9f8c5f5
歡迎關注ATYUN官方公眾號
商務合作及內容投稿請聯系郵箱:bd@atyun.com
要發表評論,您必須先登錄。