003-2集合Set用法(in, not in, &,|,-,^)+字典dictionary的用法

回覆文章
cajhbb
系統管理員
文章: 903
註冊時間: 2018年 6月 30日, 02:16

003-2集合Set用法(in, not in, &,|,-,^)+字典dictionary的用法

文章 cajhbb »

003-2集合Set用法(in, not in, &,|,-,^)+字典dictionary的用法

代碼: 選擇全部

s1={1,2,3,4,5} #宣告集合s1
s2={4,5,6,7,8} #宣告集合s2
print(6 in s1) #查看6是否在s1
print(6 in s2) #查看6是否在s2
print(6 not in s1) #查看6是否不在s1
print(6 not in s2) #查看6是否不在s2
#交集.聯集
print(s1&s2) #交集
print(s1|s2) #聯集
print(s1-s2) #差集
print(s2-s1) #差集
print(s1^s2) #反交集(取不重複部份)
#-----------------------------------------
s=set("happy") #set拆解字串為集合
print(s) #重複的部份取1份
print("y" in s) #查看y有在集合內嗎?
cajhbb
系統管理員
文章: 903
註冊時間: 2018年 6月 30日, 02:16

字典dictionary的用法dic要用配對的方式 key-value呈現

文章 cajhbb »

字典dictionary的用法dic要用配對的方式 key-value呈現

代碼: 選擇全部

dic={"flower":"花","orange":"橘子","Apple":"蘋果"}
print(dic)
print(dic["Apple"])#用括號key找value
print("flower" in dic)#判斷key存在否?
print("flower" not in dic)#判斷key不存在否?
#---- 刪除key ----
print(dic)
del dic["orange"]
print(dic)
#---- 字典變數列表型態 -----
dic={y:y*2 for y in [3,4,5]}
print(dic)
回覆文章