Python集合(Set)的基本操作
1. 集合的基本概念
集合特點:
- 元素不重複
- 元素必須是不可變類型
- 元素無序
- 支持集合運算(交集、並集等)
# 創建集合
empty_set = set() # 空集合
numbers = {1, 2, 3, 4, 5}
fruits = {"蘋果", "香蕉", "橘子"}
# 從其他類型創建集合
numbers_from_list = set([1, 2, 2, 3, 3, 4]) # {1, 2, 3, 4}
chars = set("hello") # {'h', 'e', 'l', 'o'}
2. 集合操作
# 添加元素
fruits = {"蘋果", "香蕉"}
fruits.add("橘子")
fruits.update(["葡萄", "西瓜"])
# 刪除元素
fruits.remove("香蕉") # 元素不存在會報錯
fruits.discard("梨") # 元素不存在不會報錯
popped = fruits.pop() # 隨機移除一個元素
fruits.clear() # 清空集合
3. 集合運算
# 定義兩個集合
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# 交集
intersection = A & B # {4, 5}
intersection2 = A.intersection(B)
# 並集
union = A | B # {1, 2, 3, 4, 5, 6, 7, 8}
union2 = A.union(B)
# 差集
difference = A - B # {1, 2, 3}
difference2 = A.difference(B)
# 對稱差集
symmetric_diff = A ^ B # {1, 2, 3, 6, 7, 8}
symmetric_diff2 = A.symmetric_difference(B)
4. 實際應用範例
去除重複元素
# 去除列表中的重複元素
numbers = [1, 2, 2, 3, 3, 4, 4, 5]
unique_numbers = list(set(numbers)) # [1, 2, 3, 4, 5]
# 去除字符串中的重複字符
text = "hello world"
unique_chars = "".join(sorted(set(text))) # " dehlorw"
共同元素查找
# 查找多個列表的共同元素
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
list3 = [5, 6, 7, 8, 9]
common = set(list1) & set(list2) & set(list3) # {5}
5. 練習題
-
實現好友關係分析:
- 找出共同好友
- 找出獨特的好友(只是其中一人的好友)
- 計算好友總數(不重複)
-
單詞統計分析:
- 統計兩段文本的共同單詞
- 找出獨特的單詞
- 計算詞彙量