1、集合
找兩個列表當中的相同元素
friends1 = ['zero', 'kevin', 'jason', 'egon']
friends2 = ['jy', 'kevin', 'jason', 'egon']
l = []
for x in friends1: #for循環太復雜了
if x in friends2:
l.append(x)
print(l)
2、定義:
在{}內用逗號分隔開多個元素,多個元素滿足以下三個條件:
1、集合內的元素必須是不可變類型
2、集合內元素無序
3、集合內元素不能重復,重復只能留一個
s = {} # 默認空字典
s = {1,2} # s = set({1,2})
s = {1,[1,2]} 錯誤
s = {1,'a','z',4,7} # 集合內元素無序
s = {1,21,1,1,1} # 集合內元素沒有重復
s = set() # 定義空集合
3、類型轉換
set('hellollllll') # 相當於調用For循環得到“heol”,本身就是無序的
print(set([1,1,1,1,1,1])) # 返回{1}
print(set([1,1,1,1,1,1,[1,2]])) # 報錯
print(set({'k1':1,'k2':2})) # 返回的是key
4、內置方法
關系運算符
friends1 = {'zero', 'kevin', 'jason', 'egon'}
friends2 = {'jy', 'ricky', 'jason', 'egon'}
4.1 求交集:兩者共同的好友
res = friends1 & friends2
print(res)
print(friends1.intersection(friends2))
4.2 求並集:兩者所有的好友
a = friends1 | friends2
print(a)
print(friends1.union(friends2))
4.3 求差集:取friend1獨有的好友
print(friends1 - friends2)
print(friends1.difference(friends2)) #求那個調用哪個
求差集:取friend1獨有的好友
print(friends2 - friends1)
print(friends2.difference(friends1))
4.4 求兩個用戶獨有的好友們
print(friends1 ^ friends2)
print(friends1.symmetric_difference(friends2)) # 求對稱的不同
4.5 父子集:包含的關系
s1 = {1, 2, 3}
s2 = {1, 2, 4}
不存在包含關系,下面比較均為False
print(s1 > s2)
print(s1 < s2)
s11 = {1, 2, 3}
s22 = {1, 2}
print(s11 > s22) # 當s11大於或者等於s22時,才能說s11是s22的爹
print(s11.issuperset(s22)) #s1 > s2
print(s22.issubset(s11)) # s2 < s1 =>True
s1 = {1, 2, 3}
s2 = {1, 2, 3}
print(s1 == s2) # s1與s2互為父子
print(s1.issuperset(s2))
print(s2.issuperset(s1))
去重
1、只能針對不可變類型去重
print(set([1, 1, 1, 2, 2, 3]))
2、可以去重但無法保證原來的順序
l = [1, 'a', 'b', 'z', 1, 1, 2, 3, 4, 2]
l = list(set(l))
print(l)
3、自己去重的代碼
l=[
{'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_l = []
for dic in l:
if dic not in new_l:
new_l.append(dic)
print(new_l)
需要掌握的內置方法
1、discard:如果集合當中有這個成員,則把這個成員刪掉
s = {1,2,3} # 刪除元素不存在do nothing
s.discard(4) # 不會報錯
s.remove(4) # 會報錯
2、update:更新集合,也就是把新集合加進去,然后做個去重
s.update({1,3,5})
print(s)
3、pop
s.pop() #按照索引刪除
print(s)
4、add
s.add(6)
print(s)
5、其余方法全為了解
res=s.isdisjoint({3,4,5,6}) # 兩個集合完全獨立、沒有共同部分,返回True
print(res)
s.difference_update({3,4,5}) # s=s.difference({3,4,5}),也就是說先求差集,然后把集合更新去重,成為新的集合
print(s)