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

วิธีหาดัชนี (Index) ของสมาชิกในลิสต์ Python

เมธอด index() ของลิสต์ (และ sequence อื่นๆ เช่น string, tuple) ใช้หา ดัชนีของการปรากฏครั้งแรก ของสมาชิกที่ระบุ

ตัวอย่าง: หาดัชนีครั้งแรก

>> L1 = ['a', 'b', 'c', 'a', 'x']
>>> L1.index('a')
0

หาดัชนีของทุกครั้งที่ปรากฏ (All Occurrences)

ใช้ enumerate() ซึ่งคืน iterator ของ (index, value) คู่กัน

>> L1 = ['a', 'b', 'c', 'a', 'x']
>>> [i for i, j in enumerate(L1) if j == 'a']
[0, 3]

# หรือใช้ for loop
>>> for i, j in enumerate(L1):
...     if j == 'a':
...         print(i)
0
3

การจัดการข้อผิดพลาด

หากสมาชิกไม่มีในลิสต์ index() จะโยน ValueError ควรตรวจสอบก่อนด้วย in หรือใช้ try-except:

>> 'z' in L1
False
>>> try:
...     L1.index('z')
... except ValueError:
...     print("Not found")
Not found