Python 集合(一)

用書 PYTHON王者歸來 作者洪錦魁

建立集合

使用 { }或 set 建立集合

集合是唯一且無序的

A = {1,2,2,3}

print(A)

print(type(A))

B =set(“CanYouHear?”)

print(B)

C =set([“Hi”,”Elle”,”HI”])

print(C)

D = {}

print(type(D))

E = set(D)

print(type(E))

執行結果

刪除重複資料

利用唯一性這一個特點,對於刪除重複資料這一點很有效率

可先用Set把串列資料轉成集合,再把集合用List轉成串列就可以了

A = [1,2,2,3,4,4,4,4,9,5,5]

print(A)

B = set(A)

C = list(B)

print(C)

執行結果

集合的操作

交集 (intersection) 數學符號 : A∩B PYTHON符號 : &

聯集(union) : 數學符號 : A ∪ B PYTHON符號 : |

差集(difference) : PYTHON符號 : : –

對稱差集(symmetric difference) PYTHON符號 : ^

等於 PYTHON符號 : ==

不等於 PYTHON符號 : !=

是成員 PYTHON : in

不是成員 PYTHON符號 : not in

English = {“Abby”,”Susan”,”Cathy”,”Kiki”}

Japanese ={“Lucy”,”Ally”,”Nini”,”Kiki”}

print(English,”English”)

print(Japanese,”Japanes”)

#交集 (intersection)

intersection01 = English & Japanese

intersection02 = English.intersection(Japanese)

print(intersection01,”交集”)

print(intersection02,”交集”)

#聯集(union)union01 = English | Japanese

union02 = English.union(Japanese)

print(union01,”聯集”)

print(union02,”聯集”)

#差集(difference)

English_only = English – Japanese

English_only01 = English.difference(Japanese)

Japanese_only = Japanese – English

Japanese_only01 = Japanese.difference(English)

print(English_only,”差集”)

print(English_only01,”差集”)print(Japanese_only,”差集”)

print(Japanese_only01,”差集”)

#對稱差集(symmetric difference)

NO = English ^ Japanese

NO1 = English.symmetric_difference(Japanese)

print(NO,”對稱差集”)

print(NO1,”對稱差集”)

執行結果

A = {1,2,3,4,5}

B = {2,4,3,1,5}

C = {9,8}

print(“A=B?”,A==B)

print(“A=C?”,A==C)

print(“A=B?”,A!=B)

print(“A=C?”,A!=C)
D = set(“apple”)

print(“a在裡面嗎?”,”a”in D)

print(“f在裡面嗎?”,”f”in D)

print(“a不在裡面嗎?”,”a” not in D)

print(“f不在裡面嗎?”,”f”not in D)

for word in D:   

print( word )

E = {“Nini”,”Susan”,”Gigi”}

print(“Nini在裡面嗎?”,”Nini”in E)

print(“MIMI在裡面嗎?”,”MIMI”in E)

print(“Nini不在裡面嗎?”,”Nini” not in E)

print(“MIMI不在裡面嗎?”,”MIMI” not in E)

for name in E:   

print(name)

執行結果

執行結果