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

Python – ดึงสมาชิกที่มีค่าเท่ากับดัชนี

เมื่อต้องการดึงสมาชิกที่มีค่าเท่ากับดัชนี (index) ของมันในลิสต์ สามารถใช้ลูป iteration และ enumerate() ได้

ตัวอย่าง

my_list = [33, 1, 2, 45, 41, 13, 6, 9]
print("The list is :")
print(my_list)
my_result = []
for index, element in enumerate(my_list):
    if index == element:
        my_result.append(element)
print("The result is :")
print(my_result)

ผลลัพธ์

The list is : [33, 1, 2, 45, 41, 13, 6, 9]
The result is : [1, 2, 6]

คำอธิบาย

  • กำหนดลิสต์ตัวเลขและแสดงผล

  • สร้างลิสต์ว่างผลลัพธ์

  • ใช้ enumerate() วนลูปได้ทั้งดัชนีและค่า

  • ตรวจสอบ if index == element ถ้าเท่ากันเพิ่มในผลลัพธ์

  • แสดงผลลัพธ์ (ดัชนี 1=ค่า1, ดัชนี2=ค่า2, ดัชนี6=ค่า6)