Check if Element Exists in Tuple
เมื่อต้องการตรวจสอบว่าเอลีเมนต์หนึ่งมีอยู่ใน Tuple หรือไม่ สามารถใช้ Loop ธรรมดา หรือ Operator in ได้
Tuple เป็น Immutable
Tuple ไม่สามารถเปลี่ยนแปลงค่าได้หลังสร้างแล้ว เหมาะสำหรับข้อมูลที่ต้องการ Read-only
ตัวอย่างโค้ด (ใช้ Loop)
my_tuple_1 = (23, 45, 12, 56, 78, 0)
print("The first tuple is : ")
print(my_tuple_1)
N = 12
print("The value of 'N' has been initialized")
my_result = False
for elem in my_tuple_1:
if N == elem:
my_result = True
break
print("Does the tuple contain the value mentioned ?")
print(my_result)
ผลลัพธ์
The first tuple is : (23, 45, 12, 56, 78, 0) The value of 'N' has been initialized Does the tuple contain the value mentioned ? True
คำอธิบาย
- กำหนด Tuple และแสดงผล
- กำหนดค่าที่ต้องการค้นหา
N = 12 - วนลูปผ่าน Tuple ถ้าพบค่าเท่ากับ N ให้ตั้ง Flag เป็น True และ Break
- เก็บผลลัพธ์และแสดง
วิธีที่ง่ายกว่า: ใช้ Operator in
my_tuple_1 = (23, 45, 12, 56, 78, 0)
N = 12
# Pythonic way
my_result = N in my_tuple_1
print(my_result) # True
# ตรงข้าม
print(N not in my_tuple_1) # False
หา Index ของ Element (ถ้ามี)
my_tuple = (23, 45, 12, 56, 78, 0)
N = 12
if N in my_tuple:
index = my_tuple.index(N)
print(f"Found at index {index}") # Found at index 2
else:
print("Not found")
นับจำนวนครั้งที่ปรากฏ
my_tuple = (1, 2, 2, 3, 2, 4)
print(my_tuple.count(2)) # 3
ประสิทธิภาพ
Operator in บน Tuple ใช้เวลา O(n) ตรวจสอบแบบ Linear Search หากค้นหาบ่อยๆ ควรแปลงเป็น Set ก่อน (O(1)):
my_tuple = (23, 45, 12, 56, 78, 0)
my_set = set(my_tuple) # O(n) ครั้งแรก
print(12 in my_set) # O(1) ต่อครั้งถัดไป