標籤:and intersect 比較 union 集合 不能 res bsp 漢字
集合的定義:
集合和列表([ ]) 與 字典 ( { }) 不同,沒有特別的特別的文法格式。可以使用set () 建立。
集合約字典一樣是無序的。也是不具有重複性的。因此可以把列表變成集合進行去重。
集合具有特別的關係效能,交集,並集,差集等。
# hanbb come on!list1 = [1,4,5,7,3,6,7,9] # 列表s1 = set(list1) # remove repeat,such as 7 ; 自動去重 (列錶轉化為集合)s2 = set([1,6,0,66,22,8,4]) # another way express sets3 = set("hello") # 這是字元變成集合嗎?print(s3) # {‘h‘, ‘o‘, ‘l‘, ‘e‘}print(s2) # {0, 2, 66, 4, 6, 8, 22}print(s1) # {1, 3, 4, 5, 6, 7, 9}
集合的基本操作:新增;移除;複製;求長度(沒有修改?)
# basic operation# Add ones1.add(‘BB8‘)print(s1) # {1, 3, 4, 5, 6, 7, ‘BB8‘, 9}# add mores1.update( ["豬八戒","孫悟空"] ) # 注意[] # {1, ‘孫悟空‘, 3, 4, 5, 6, 7, ‘BB8‘, 9, ‘豬八戒‘}print(s1)# s1.update(2,4,6)s1.update([2,4,6]) # {1, 2, 3, 4, 5, 6, 7, 9, ‘豬八戒‘, ‘BB8‘, ‘孫悟空‘}print(s1)s1.update("BB7") # update"BB7" and add "BB8" 區別明顯 # {1, 2, 3, 4, 5, 6, 7, 9, ‘7‘, ‘BB8‘, ‘孫悟空‘, ‘豬八戒‘, ‘B‘}print(s1)# Remove# s1.remove("1","2","3") # 不能移除多個 # remove() takes exactly one argument (3 given)# s1.remove(‘1‘) # 資料會出錯,為啥呀 # s1.remove(‘1‘)s1.remove(‘B‘) # 字母不會,漢字也不會 # {1, 2, 3, 4, 5, 6, 7, 9, ‘豬八戒‘, ‘孫悟空‘, ‘BB8‘, ‘7‘}print(s1)# copys4 = s2.copy()print(s2)# lengthprint(len(s1)) # 12
集合的關係運算:交集,並集,差集(兩個集合位置有影響),對稱差集。
# relationshipprint(s1.intersection(s2)) # {1, 4, 6}print(s1.union(s2)) # {0, 1, 2, 3, 4, 5, 6, 7, 66, 9, 8, ‘7‘, ‘BB8‘, 22, ‘豬八戒‘, ‘孫悟空‘}print(s1.difference(s2)) # 在1中,不在2中 # {‘BB8‘, 2, 3, ‘7‘, 5, 7, 9, ‘孫悟空‘, ‘豬八戒‘}print(s2.difference(s1)) # 在2中,不在1中 # {0, 8, 66, 22}print(s1.symmetric_difference(s2)) # 對稱差集(項在t或s中,但不會同時出現在二者中) # {0, 66, 2, ‘7‘, 3, 5, 8, 7, 9, ‘孫悟空‘, 22, ‘豬八戒‘, ‘BB8‘}
集合值的訪問:
# 訪問集合值print("1" in s1) # Falseprint("BB8" in s1) # True
print("1" not in s1) # Truefor i in s1: print(i) ‘‘‘1234567孫悟空9BB87豬八戒‘‘‘
集合還是比較容易理解和掌握的,還有操作符號的運算。
集合的定義,操作及運算 (Python)