集合 Set
不能有重複元素(會自動去重)
元素沒有固定順序
每次輸出順序都不壹樣(所以不能用索引)
交集(&)
聯集(|)
差集(-)
反交集(^)
字典
鍵值對(Key-Value Pair)
一個key對一個Value
[Key]=Value
Python裡面若直接使用花括號{}=字典
d = {"apple": "蘋果", "bug": "蟲蟲"}
備註:
dict() = 開啟字典工廠,造一個新的字典
d = dict(apple="蘋果", bug="蟲蟲")
不是dic() # ❌ NameError: name 'dic' is not defined
除非你自己先定義 dic = dict,否則不存在這個東西
補充:我容易搞混的所以補充幫助釐清
一般函式:做事情(計算 / 邏輯)
建構子函式:生東西(建立容器物件)
呼叫函式:就是在名稱後面加 (),讓程式執行
例如:print()、len()、dict()
2.自定義函式 (user-defined function) 自己用 def 定義
def add(a, b):
return a + b
print(add(3, 5)) # 8
以後呼叫 add(a,b) 就會做a+b的計算
d = dict() # 呼叫建構子 → 得到一個新的空字典 {}
l = list() # 呼叫建構子 → 得到一個新的空 list []
s = set() # 呼叫建構子 → 得到一個新的空 set set()
一般函式 = 「做事的程式」
建構子函式 = 「造東西的程式」(容器)
一般函式 做邏輯、處理資料、回傳結果
add(3,5) → 8
建構子函式 建立新的物件 / 容器
dict() → {}
add(2, 3) # 5
dict() # {}
刪除鍵值對(del)
從列表建立字典
以列表的資料為基礎建立字典
判斷資料是否存在: 使用 in / not in 運算符號
s1={1,2,3}
print(3 in s1) #True
print(3 not in s1) #False
交集(&):取兩個集合中,相同資料
s1={3,4,5}
s2={4,5,6,7}
s3=s1&s2
print(s3)={4,5}
聯集(|):取兩個集合中,所有資料(不重複取
s1={3,4,5}
s2={4,5,6,7}
s3=s1|s2
print(s3)={3,4,5,6,7}
差集(-):
順序有差
s1={3,4,5}
s2={4,5,6,7}
從s1中,減去與s2重複的部分
s3=s1-s2
print(s3)={3}
從s2中,減去與s1重複的部分
s3=s2-s1
print(s3)={6,7}
反交集(^):取兩個集合中,“不重疊”的部分
s1={3,4,5}
s2={4,5,6,7}
s3=s1^s2
print(s3)={3,6,7}
set()
是一個函式,用來把「可迭代物件 (iterable)」轉成集合
例子:
s=set("Hello")
print(s) #將集合存入變數s
#{'H', 'e', 'l', 'o'} (l不重複)
字串 "Hello" 本身就是一個可迭代物件(可以一個字母一個字母走訪)。
所以 set("Hello") 會把字串拆成單個字元,再放進集合(不重複)
不存s變數
適合只需要看到結果,不會再用到集合
print(set("Hello"))
字典的運算
key-value 配對
變數 dic[key] #value
dic={"apple":"蘋果","bug":"蟲蟲"}
print(dic["apple"])
#蘋果
更改value
dic={"apple"}="大蘋果"
print(dic["apple"])
#大蘋果
判斷key是否存在 in / not in
dic={"apple":"蘋果","bug":"蟲蟲"}
print(dic["apple" in dic])
#True
print(dic["bug" not in dic])
#False
使用del(),刪除字典中的鍵值對(key-value pair)
dic={"apple":"蘋果","bug":"蟲蟲"}
print(dic)
#{"apple":"蘋果","bug":"蟲蟲"}
del("apple")
print(dic)
#{"bug":"蟲蟲"}
用列表當基礎去產生字典
除了鍵值對
也可用數學運算的方式來表達key-value:
現在令key為x,value為x*2
dic={x:x*2 for x in [列表]}
dic={x:x*2 for x in [3,4,5]}
print(dic)
#{3:6,4:8,5:10}