時間計測 II
講義でお話ししたように、ほとんどの場合、リスト内包表記は for ループよりも高速です。
このデモでは、リスト内包表記と for ループの効率差がごくわずかで、どちらを選んでもこの単純な処理が瞬時に終わるケースをご覧いただきます。
リスト words には、インターネットから取得したランダムな単語が入っています。ここから、先頭の文字が b の単語だけを残した listlet というリストを作成します。
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))