เราสามารถเข้าถึงองค์ประกอบแต่ละตัวของรายการได้โดยใช้วงเล็บ [] และหมายเลขดัชนี แต่เมื่อเราต้องการเข้าถึงดัชนีบางส่วน เราไม่สามารถใช้วิธีนี้ได้ เราต้องใช้วิธีดังต่อไปนี้
ใช้สองรายการ
ในวิธีนี้ พร้อมกับรายการเดิม เราใช้ดัชนีเป็นอีกรายการหนึ่ง จากนั้นใช้ลูป for เพื่อวนผ่านดัชนีและนำค่าเหล่านั้นไปใช้กับรายการหลักเพื่อดึงค่า
ตัวอย่าง
given_list = ["Mon", "Tue", "Wed", "Thu", "Fri"]
index_list = [1, 3, 4]
# พิมพ์รายการ
print("Given list : " + str(given_list))
print("List of Indices : " + str(index_list))
# ใช้ list comprehension
res = [given_list[n] for n in index_list]
# ได้ผลลัพธ์
print("Result list : " + str(res))
ผลลัพธ์
การรันโค้ดข้างต้นจะได้ผลดังนี้ −
Given list : ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] List of Indices : [0, 1, 2, 3, 4] Result list : ['Tue', 'Thu', 'Fri']
ใช้ map และ __getitem__
แทนที่จะใช้ลูป for เราสามารถใช้ map ร่วมกับเมธอด __getitem__ เพื่อให้ได้ผลลัพธ์เดียวกัน
ตัวอย่าง
given_list = ["Mon", "Tue", "Wed", "Thu", "Fri"]
index_list = [1, 3, 4]
# พิมพ์รายการ
print("Given list : " + str(given_list))
print("List of Indices : " + str(index_list))
# ใช้ list comprehension
res = list(map(given_list.__getitem__, index_list))
# ได้ผลลัพธ์
print("Result list : " + str(res))
ผลลัพธ์
การรันโค้ดข้างต้นจะได้ผลดังนี้ −
Given list : ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] List of Indices : [1, 3, 4] Result list : ['Tue', 'Thu', 'Fri']