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

Set Types ใน Python: set และ frozenset


Set เป็นคอลเลกชันของออบเจ็กต์ที่ไม่ซ้ำกัน (distinct) และไม่มีลำดับ ใช้สำหรับการดำเนินการทางคณิตศาสตร์เช่น union, intersection, difference และลบค่าซ้ำ

Set ไม่บันทึกตำแหน่ง ไม่รองรับ indexing หรือ slicing

มี 2 ประเภท: set (mutable) และ frozenset (immutable)

เมธอดและออปอเรชันหลัก

เมธอด/ออปอเรชันคำอธิบาย
len(s)จำนวนอิลิเมนต์
x in s / y not in sตรวจสอบสมาชิกใน set
isdisjoint(other_set)True ถ้าไม่มีอิลิเมนต์ร่วมกัน
issuperset(other_set)True ถ้าทุกอิลิเมนต์ของ other_set อยู่ใน set ปัจจุบัน
union(other_set)คืน set ใหม่รวมทุกอิลิเมนต์
intersection(other_set)คืน set ใหม่ของอิลิเมนต์ร่วม
difference(other_set)คืน set ที่มีอิลิเมนต์ของ set แรก ยกเว้นที่ซ้ำ
add(elem)เพิ่มอิลิเมนต์
discard(elem)ลบอิลิเมนต์ (ไม่ error ถ้าไม่มี) ต่างจาก remove() ที่ raise KeyError

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

mySet1 = {1, 2, 5, 6}
mySet2 = {8, 5, 3, 4}
mySet3 = set(range(15))  # 0-14
mySet4 = {10, 20, 30, 40}

print(mySet1.union(mySet2))
print(mySet1.intersection(mySet2))
print(mySet1.difference(mySet2))
print(mySet3.issuperset(mySet1))
print(mySet1.isdisjoint(mySet4))
mySet4.add(45)
print(mySet4)
mySet4.discard(40)
print(mySet4)

ผลลัพธ์

{1, 2, 3, 4, 5, 6, 8}
{5}
{1, 2, 6}
True
True
{40, 10, 20, 45, 30}
{10, 20, 45, 30}