เมื่อรายการ Python มีค่าเช่น true หรือ false และ 0 หรือ 1 จะเรียกว่า binary list ในบทความนี้ เราจะนำรายการไบนารีและค้นหาดัชนีของตำแหน่งที่องค์ประกอบรายการเป็นจริง
พร้อมแจงนับ
ฟังก์ชันแจกแจงแยกองค์ประกอบทั้งหมดจากรายการ เราใช้ a in condition เพื่อตรวจสอบว่าค่าที่สกัดออกมาเป็นจริงหรือไม่
ตัวอย่าง
listA = [True, False, 1, False, 0, True]
# printing original list
print("The original list is :\n ",listA)
# using enumerate()
res = [i for i, val in enumerate(listA) if val]
# printing result
print("The indices having True values:\n ",res) ผลลัพธ์
การเรียกใช้โค้ดข้างต้นทำให้เราได้ผลลัพธ์ดังต่อไปนี้ -
The original list is : [True, False, 1, False, 0, True] The indices having True values: [0, 2, 5]
ด้วยการประคบ
โดยใช้การบีบอัด เราจะวนซ้ำแต่ละองค์ประกอบในรายการ สิ่งนี้จะแสดงเฉพาะองค์ประกอบที่มีค่าเป็นจริงเท่านั้น
ตัวอย่าง
from itertools import compress
listA = [True, False, 1, False, 0, True]
# printing original list
print("The original list is :\n ",listA)
# using compress()
res = list(compress(range(len(listA)), listA))
# printing result
print("The indices having True values:\n ",res) ผลลัพธ์
การเรียกใช้โค้ดข้างต้นทำให้เราได้ผลลัพธ์ดังต่อไปนี้ -
The original list is : [True, False, 1, False, 0, True] The indices having True values: [0, 2, 5]