測量時間 II
正如我們在課堂上討論的,多數情況下,串列生成式(list comprehension)比 for 迴圈更快。
在這個示範中,你會看到一種情況:串列生成式與 for 迴圈在效率上的差異非常小,以致於不論選哪一種方法,都能立刻完成這個簡單任務。
在串列 words 中,包含從網路下載的隨機單字。我們想建立另一個名為 listlet 的串列,只保留以字母 b 開頭的單字。
如果你不熟悉在 Python 中處理字串:每個字串都有 .startswith() 屬性,用來判斷該字串是否以特定字母或片語開頭,並回傳 True/False。
本練習屬於課程
使用 pandas 撰寫高效程式碼
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Store the time before the execution
start_time = time.___()
# Execute the operation
letlist = [wrd for wrd in words if wrd.startswith('b')]
# Store and print the difference between the start and the current time
total_time_lc = time.time() - ___
print('Time using list comprehension: {} sec'.format(total_time_lc))