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

Python – หาดัชนีลบของสมาชิกในลิสต์

เมื่อต้องการหาดัชนีลบ (negative index) ของสมาชิกในลิสต์ สามารถใช้ len() และ index() ได้

ตัวอย่าง

my_list = [52, 47, 18, 22, 23, 57, 13]
print("The list is :")
print(my_list)
my_key = 22
print("The value of key is ")
print(my_key)
my_result = len(my_list) - my_list.index(my_key)
print("The result is :")
print(my_result)

ผลลัพธ์

The list is : [52, 47, 18, 22, 23, 57, 13]
The value of key is 22
The result is : 4

คำอธิบาย

  • กำหนดลิสต์ตัวเลขและค่าที่ต้องการหา (my_key)

  • ใช้ my_list.index(my_key) หาดัชนีบวก (0-based) ได้ 3

  • คำนวณดัชนีลบ: len(my_list) - positive_index = 7 - 3 = 4 (หมายถึง -4 หรือตำแหน่งที่ 4 จากท้าย)

  • แสดงผลลัพธ์