Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python - หาตำแหน่งครั้งสุดท้ายของสมาชิกในลิสต์

หา index ของครั้งสุดท้ายที่สมาชิกปรากฏในลิสต์

วิธีที่ 1: กลับลิสต์แล้วหา index

words = ['eat', 'sleep', 'drink', 'sleep', 'drink', 'sleep', 'go', 'come']
element = 'sleep'

words.reverse()
index = words.index(element)
print(len(words) - index - 1)  # 5

วิธีที่ 2: ใช้ enumerate + max

words = ['eat', 'sleep', 'drink', 'sleep', 'drink', 'sleep', 'go', 'come']
element = 'sleep'

final_index = max(i for i, item in enumerate(words) if item == element)
print(final_index)  # 5

สรุป

วิธี enumerate + max อ่านง่ายและไม่ต้องแก้ไขลิสต์ต้นฉบับ