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

ทดสอบว่า Tuple มีค่า K อยู่หรือไม่ใน Python

Test if Tuple Contains K Value

เมื่อต้องการตรวจสอบว่า Tuple มีค่า K อยู่หรือไม่ สามารถใช้ any(), map() และ Lambda Function ได้

ฟังก์ชันที่ใช้

  • Lambda: Anonymous Function ด้วย lambda
  • map(): ใช้ Function กับทุก Item ใน Iterable
  • any(): คืน True ถ้ามี Element ใด Element หนึ่งเป็น True

ตัวอย่างโค้ด

my_tuple = (67, 45, 34, 56, 99, 123, 10, 56)
print("The tuple is : ")
print(my_tuple)

K = 67
print("The value of 'K' has been initialized")

# Lambda เช็ค elem is K, map ใช้กับทุกตัว, any เช็คว่ามี True ไหม
my_result = any(map(lambda elem: elem is K, my_tuple))

print("Does tuple contain the K value ?")
print(my_result)

ผลลัพธ์

The tuple is : (67, 45, 34, 56, 99, 123, 10, 56)
The value of 'K' has been initialized
Does tuple contain the K value ? True

คำอธิบาย

  • กำหนด Tuple และแสดงผล
  • กำหนด K = 67
  • lambda elem: elem is K สร้างฟังก์ชันเช็ค Identity (is)
  • map(...) ใช้กับทุก Element ได้ Iterator ของ Boolean
  • any(...) เช็คว่ามี True อย่างน้อย 1 ตัว
  • เก็บผลลัพธ์และแสดง

⚠️ ข้อควรระวัง: is vs ==

# is ตรวจสอบ Identity (Object เดียวกัน)
# == ตรวจสอบ Equality (ค่าเท่ากัน)

# สำหรับ Integer ขนาดเล็ก (-5 ถึง 256) Python Cache ไว้ -> is ทำงานได้
# แต่ Integer ใหญ่ อาจเป็น Object คนละตัว
K = 1000
t = (1000,)
print(K is t[0])   # False (อาจเป็น True/False ขึ้นกับ Implementation)
print(K == t[0])   # True เสมอ

# แนะนำ: ใช้ == สำหรับเปรียบเทียบค่า
my_result = any(map(lambda elem: elem == K, my_tuple))

วิธีที่ง่ายและถูกต้องที่สุด

# Pythonic Way - ใช้ in Operator
my_result = K in my_tuple
print(my_result)  # True

# นับจำนวนครั้ง
count = my_tuple.count(K)
print(count)  # 1

ประสิทธิภาพ

MethodTimeNote
K in tupleO(n)Linear Search, สง่ายที่สุด
any(map(...))O(n)Overhead ของ Function Call
set(tuple) then inO(n) + O(1)ดีถ้าค้นหาหลายครั้ง