การใช้ enumerate
เริ่มเข้าใจการใช้ iterator ได้ดีมากเลย ต่อไปจะได้ลองใช้ฟังก์ชัน enumerate() ซึ่งเป็นหนึ่งในแนวคิดที่เพิ่งได้เรียนไป
enumerate() จะคืนค่าเป็นออบเจกต์ประเภท enumerate ที่สร้างลำดับของ tuple โดยแต่ละ tuple จะเป็นคู่ของ index-value
ในแบบฝึกหัดนี้ มีลิสต์ของสตริงชื่อ mutants ให้พร้อมแล้ว จงฝึกใช้ enumerate() กับลิสต์นี้ โดยการพิมพ์ลิสต์ของ tuple ออกมา และ unpack tuple ด้วย for loop
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Python Toolbox
คำแนะนำการฝึกหัด
- สร้างลิสต์ของ tuple จาก
mutantsแล้วกำหนดผลลัพธ์ให้กับตัวแปรmutant_listโดยใช้enumerate()เพื่อสร้าง tuple และแปลงผลลัพธ์เป็นลิสต์ด้วยlist() - เติม
forloop แรกให้สมบูรณ์ โดย unpack tuple ที่ได้จากการเรียกenumerate()บนmutantsใช้index1สำหรับ index และvalue1สำหรับค่าเมื่อ unpack tuple - เติม
forloop ที่สองในลักษณะเดียวกับ loop แรก แต่คราวนี้ให้เปลี่ยน index เริ่มต้นเป็น1โดยส่งค่าดังกล่าวเป็นอาร์กิวเมนต์ให้กับพารามิเตอร์startของenumerate()ใช้index2สำหรับ index และvalue2สำหรับค่าเมื่อ unpack tuple
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# Create a list of strings: mutants
mutants = ['charles xavier',
'bobby drake',
'kurt wagner',
'max eisenhardt',
'kitty pryde']
# Create a list of tuples: mutant_list
mutant_list = ____
# Print the list of tuples
print(mutant_list)
# Unpack and print the tuple pairs
for ____ in ____:
print(index1, value1)
# Change the start index
for ____ in ____:
print(index2, value2)