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

First Occurrence of True Number ใน Python: หาตำแหน่งตัวเลขไม่ศูนย์แรก

ได้ลิสต์ตัวเลข ต้องการดัชนีของตัวเลขแรกที่ไม่ใช่ 0

วิธี 1: ใช้ enumerate กับ next()

listA = [0, 0, 13, 4, 17]
res = next((i for i, v in enumerate(listA) if v), None)
print(res)  # 2

วิธี 2: ใช้ next, filter, lambda

listA = [0, 0, 13, 4, 17]
res = listA.index(next(filter(lambda x: x != 0, listA)))
print(res)  # 2

สรุป

วิธี 1 ใช้ Generator Expression มีประสิทธิภาพดีกว่า (หยุดทันทีที่เจอ) วิธี 2 ใช้ Filter แล้วหา Index อาจช้ากว่าเล็กน้อย