Check if Tuple is Subset of Another Tuple
เมื่อต้องการตรวจสอบว่า Tuple หนึ่งเป็น Subset ของอีก Tuple สามารถใช้เมธอด issubset() ได้
issubset() Method
set1.issubset(set2) คืนค่า True ถ้าทุก Element ของ Set1 อยู่ใน Set2 ด้วย มิฉะนั้นคืน False
เนื่องจาก Tuple ไม่มีเมธอด issubset() ตรงๆ จึงต้องแปลงเป็น Set ก่อน
ตัวอย่างโค้ด
my_tuple_1 = (87, 90, 31, 85)
my_tuple_2 = (34, 56, 12, 5)
print("The first tuple is :")
print(my_tuple_1)
print("The second tuple is :")
print(my_tuple_2)
# แปลง Tuple ที่ 2 เป็น Set แล้วเช็คว่าเป็น Subset ของ Tuple 1 หรือไม่
my_result = set(my_tuple_2).issubset(my_tuple_1)
print("Is the second tuple a subset of the first tuple ? ")
print(my_result)
ผลลัพธ์
The first tuple is : (87, 90, 31, 85) The second tuple is : (34, 56, 12, 5) Is the second tuple a subset of the first tuple ? False
คำอธิบาย
- กำหนด Tuple 2 ตัว และแสดงผล
- แปลง
my_tuple_2เป็น Set แล้วเรียก.issubset(my_tuple_1) - Python จะแปลง
my_tuple_1เป็น Set อัตโนมัติในการเปรียบเทียบ - ผลลัพธ์ False เพราะ Element ของ Tuple 2 (34, 56, 12, 5) ไม่อยู่ใน Tuple 1 เลย
- แสดงผลบนคอนโซล
ตัวอย่างที่เป็น True
t1 = (1, 2, 3, 4, 5)
t2 = (2, 4)
print(set(t2).issubset(t1)) # True
t3 = (1, 2, 3)
t4 = (1, 2, 3, 4)
print(set(t3).issubset(t4)) # True
เมธอดอื่น: ใช้ <= Operator
# เทียบเท่ากัน
print(set(t2) <= set(t1)) # True (Subset)
print(set(t2) < set(t1)) # True (Proper Subset - ต้องไม่เท่ากัน)
หมายเหตุเกี่ยวกับ Duplicate
# Set จะลบ Duplicate ออก
t1 = (1, 2, 2, 3)
t2 = (2, 2)
print(set(t2).issubset(t1)) # True - แม้ t2 มี 2 สองตัว แต่ Set ถือว่าแค่ตัวเดียว