iT邦幫忙

2025 iThome 鐵人賽

DAY 7
0
Software Development

來一場軟體開發學習之旅系列 第 7

Day 7:集合 ─ 處理不重複的資料

  • 分享至 

  • xImage
  •  

假設你有一份名單,其中有人重複出現:
students = ["Allen", "Lily", "Tom", "Lily", "Allen"]

如果你要知道有哪些獨一無二的學生名字,集合(Set)就能幫上忙。

  1. 建立集合
    students = {"Allen", "Lily", "Tom", "Lily", "Allen"}
    print(students) # {'Allen', 'Tom', 'Lily'}

特點:
不會有重複元素
沒有順序(無法用索引存取,如 students[0] 會錯誤)

  1. 基本操作
    fruits = {"apple", "banana", "cherry"}
    #新增元素
    fruits.add("orange")
    print(fruits)
    #移除元素
    fruits.remove("banana")
    print(fruits)
    #判斷是否存在
    print("apple" in fruits) # True
    print("grape" in fruits) # False

集合最強大的地方,就是能像數學一樣做交集、聯集、差集。
3. 集合的數學運算
A = {"apple", "banana", "cherry"}
B = {"banana", "cherry", "durian"}

print(A | B) # 聯集: {'apple', 'banana', 'cherry', 'durian'}
print(A & B) # 交集: {'banana', 'cherry'}
print(A - B) # 差集: {'apple'}
print(B - A) # 差集: {'durian'}

這特別適合用在去除重複資料、比對兩份清單。

  1. 真實案例
    網站使用者分析
    A = {"Allen", "Tom", "Lily"} → 今日登入的使用者
    B = {"Tom", "Lily", "Mary"} → 購物的使用者
    A & B → 既登入又購物的使用者
    A - B → 只登入但沒購物的使用者

班級名單比對
一個班的學生名單 A
出席的學生名單 B
A - B → 缺席的學生名單

學會了集合(Set)的特性與應用:去除重複、數學運算、比對資料。
明天,將開始探索檔案操作(File Handling),學會如何讓程式讀寫檔案,把資料存起來或取出來,進一步讓程式可以記憶。


上一篇
Day 6:字典 ─ 讓資料有名字
下一篇
Day 8:檔案操作 ─ 讓程式有記憶
系列文
來一場軟體開發學習之旅9
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言