# Python集合

• 集合中的元素不能重複。
• 集合中的元素是不可變的(不能被修改)，但集合作爲一個整體是可變的。
• 附加到python集合中的任何元素不需要索引。所以集合不支持任何索引或切片操作。

## 集合操作

python中的集合通常用於像聯合，相交，異同和補充等數學運算。下面創建一個集合，訪問它的元素並執行這些數學運算。參考以下示例代碼 -

``````Days=set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"])
Months={"Jan","Feb","Mar"}
Dates={21,22,17}
print(Days)
print(Months)
print(Dates)``````

``````{'Wed', 'Fri', 'Tue', 'Mon', 'Thu', 'Sun', 'Sat'}
{'Feb', 'Mar', 'Jan'}
{17, 21, 22}``````

``````Days=set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"])

for d in Days:
print(d)``````

``````Wed
Sun
Fri
Tue
Mon
Thu
Sat``````

``````Days=set(["Mon","Tue","Wed","Thu","Fri","Sat"])

print(Days)``````

``{'Wed', 'Sat', 'Thu', 'Mon', 'Sun', 'Tue', 'Fri'}``

``````Days=set(["Mon","Tue","Wed","Thu","Fri","Sat"])

print(Days)``````

``{'Tue', 'Fri', 'Wed', 'Sat', 'Thu', 'Mon'}``

``````DaysA = set(["Mon","Tue","Wed"])
DaysB = set(["Wed","Thu","Fri","Sat","Sun"])
AllDays = DaysA|DaysB
print(AllDays)``````

``{'Mon', 'Sun', 'Thu', 'Tue', 'Wed', 'Fri', 'Sat'}``

``````DaysA = set(["Mon","Tue","Wed"])
DaysB = set(["Wed","Thu","Fri","Sat","Sun"])
AllDays = DaysA & DaysB
print(AllDays)``````

``{'Wed'}``

``````DaysA = set(["Mon","Tue","Wed"])
DaysB = set(["Wed","Thu","Fri","Sat","Sun"])
AllDays = DaysA - DaysB
print(AllDays)``````

``{'Mon', 'Tue'}``

``````DaysA = set(["Mon","Tue","Wed"])
DaysB = set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"])
SubsetRes = DaysA <= DaysB
SupersetRes = DaysB >= DaysA
print(SubsetRes)
print(SupersetRes)``````

``````True
True``````