การวัดเวลา II
ดังที่ได้กล่าวถึงในบทเรียน ในกรณีส่วนใหญ่ list comprehension จะเร็วกว่า for loop
ในแบบฝึกหัดนี้ คุณจะเห็นกรณีที่ list comprehension และ for loop มีความแตกต่างด้านประสิทธิภาพน้อยมาก จนทั้งสองวิธีสามารถทำงานนี้ได้อย่างรวดเร็วเท่ากัน
ใน list ชื่อ words มีคำสุ่มที่ดาวน์โหลดมาจากอินเทอร์เน็ต เราต้องการสร้าง list ใหม่ชื่อ listlet โดยเก็บเฉพาะคำที่ขึ้นต้นด้วยตัวอักษร b เท่านั้น
หากยังไม่คุ้นเคยกับการจัดการ string ใน Python แต่ละ string มี attribute .startswith() ซึ่งจะคืนค่า True หรือ False ขึ้นอยู่กับว่า string นั้นขึ้นต้นด้วยตัวอักษรหรือวลีที่ระบุหรือไม่
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
การเขียนโค้ดที่มีประสิทธิภาพด้วย 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))