定義
定義:在{}中用逗號隔開,集合具備以下3個特點:
1.每個元素必須是不可變類型
2.集合內沒有重復元素
3.集合內元素無序
my_set = {1, 2, 3, 4}
# 本質上
my_set = set({1, 2, 3, 4})
# 注意1:列表是索引對應值,字典是key對應值,均可以取得單個值.
# 而集合類型既沒有索引也沒有key值相對應,所以無法取得單個的值.對集合來說
# 主要功能在於去重與關系元素,沒有取出單個值的需求
# 注意2:{}既被用於定義字典也被用於定義集合.但是字典內的元素必須以key:value的形式.
# 如何准確的定義一個空集合?
my_set = {}
print(type(my_set))
my_set = set()
print(type(my_set))
>>>
<class 'dict'>
<class 'set'>
類型轉換
但凡能被for循環遍歷輸出的值(輸出的值不能為可變數據類型)
my_set = set([1, 2, 3, 4, 5]) >>>{1, 2, 3, 4, 5} my_set = set('string') >>>{'t', 's', 'g', 'i', 'r', 'n'} my_set = set((1, 2, 3, 4, 1)) >>>{1, 2, 3, 4} my_set = set({'name':'yyh'}) >>>{'name'}
關系運算
friends1 = {'Albert', 'Tony', 'John', 'Egon', 'Sean'}
friends2 = {'Sean', 'Sor', 'Egon'}
print(friends1 | friends2) # 求合集
print(friends1 & friends2) # 求交集
print(friends1 - friends2) # 求差集 friends1中獨有的
print(friends2 - friends1) # 求差集 friends2中獨有的
print(friends1 ^ friends2) # 對稱差集(去掉共有的好友后的合集)
print(friends1 == friends2) # 集合是否相等
print({1, 2, 3} >= {1, 2, 3}) # 包含關系
print({1, 2, 3} > {1, 2}) # 真包含關系
print({1, 2} < {1, 2, 3}) # 真子集
print({1, 2, 3} <= {1, 2, 3}) # 子集
去重
# 集合去重復有局限性,僅適用於不可變數據類型 # 集合本身是無序的, 去重之后無法保留原來的順序 my_list = ['a', 'b', 1, 'a', 'b'] my_set = set(my_list) # 列表轉集合 print(my_set) my_list = list(my_set) # 集合轉列表 print(my_list) # 去除了重復,但是打亂了順序
# 針對可變類型,並且保證順序則需要自己寫代碼實現 my_list = [ {'name': 'lili', 'age': 18, 'sex': 'male'}, {'name': 'jack', 'age': 73, 'sex': 'male'}, {'name': 'tom', 'age': 20, 'sex': 'female'}, {'name': 'lili', 'age': 18, 'sex': 'male'}, {'name': 'lili', 'age': 18, 'sex': 'male'}, ] new_list = [] for i in my_list: if i not in new_list: new_list.append(i) print(new_list)
練習
pythons = {'jason', 'egon', 'kevin', 'ricky', 'gangdan', 'biubiu'}
linuxs = {'kermit', 'tony', 'gangdan'}
print(f'即報名了python又報名了linux的學員有{pythons & linuxs}')
print(f'所有報名的學員{pythons | linuxs}')
print(f'只報名了python的學員{pythons - linuxs}')
print(f'只報名了其中一門的學員{pythons ^ linuxs}')
