[Python] Set集合、set()函數

2023/11/30閱讀時間約 3 分鐘

Set(集合) : 是一個沒有順序沒有重複元素的集合 (就像是只有Key沒有Value的字典)

因為Set沒有重複資料/元素的特性,可以用來查看2個集合元素間是否有交集、聯集、差集的關聯性。


  • 建立集合
  1. set()函數

set()函數可以建立一個空集合,也可以將串列、字串、tuple、字典轉成集合

set(要變成集合的元素)

  1. 大括號{}包住元素

初始化元素可以用{}包住元素,或是使用set()函數,如果使用set={}會建立成空的字典

line 5 : False等於0,True等於1,所以在集合當中只會保留數字

s1 = set()
s4 = set(('a','b','c','d'))
s2 = {1,2,3,4}
s3 = {1,1,2,2,3,3,3,4,5,5}
s5 = {0,1,2,3,'a','b',False,True}

print(s1)
print(s2)
print(s3)
print(s4)
print(s5)

# ========Output============
# set()
# {'b', 'd', 'c', 'a'}
# {1, 2, 3, 4}
# {1, 2, 3, 4, 5}
# {0, 1, 2, 3, 'b', 'a'}


  • 加入集合add()

將元素加入集合當中

set1 = {1,2,3,4}
set1.add('a')
set1.add("abc")

print(set1)

# ========Output============
# {1, 2, 3, 4, 'a', 'abc'}


  • 移除集合中的元素remove()、discard()
  1. remove()

刪除()內指定的元素,如果該元素不存在產生錯誤訊息

set2 = {1,2,3,4}
set2.remove(2)
set2.remove(4)

print(set2)

# ========Output============
# {1, 3}
  1. discard()

刪除()內指定的元素,如果該元素不存在不會產生錯誤訊息

set2 = {1,2,3}
set2.discard(2)
set2.discard(4)

print(set2)

# ========Output============
# {1, 3}


交集、聯集、差集、對稱差集


方法 運算子

  • 交集 a.intersection(b) a & b
  • 聯集 a.union(b) a|b
  • 差集 a.difference(b) a - b
  • 對稱差集 a.symmetric_difference(b) a ^ b





7會員
36內容數
這裡會放一些我寫過的 Leetcode 解題和學習新技術的筆記
留言0
查看全部
發表第一個留言支持創作者!