本文内容皆为作者原创,如需转载,请注明出处:https://www.cnblogs.com/xuexianqi/p/12467825.html
一:作用
1.关系运算(详情见 四.1)
friends1 = {"zero","kevin","jason","egon"} # 用户1的好友们
friends2 = {"Jy","ricky","jason","egon"} # 用户2的好友们
l = []
for x in friends1:
if x in friends2:
l.append(x) # 找到用户1和用户2的共同好友
print(l)
2.去重(详情见 四.2)
二:定义
在 {} 内通逗号隔开多个元素,多个元素满足以下条件:
1.集合内的元素必须为不可变类型
# s = {1,[1,2]} # 错误,集合内的元素必须为不可变类型
TypeError: unhashable type: 'list'
2.集合内的元素无序
s = {1,'a','z','b',4,7} # 集合内元素无序
{1, 4, 7, 'z', 'b', 'a'}
3.集合内的元素没有重复
s = {1,1,1,1,'a','z','b',4,7} # 集合内的元素不能重复
{1, 'a', 4, 7, 'z', 'b'}
了解
s = {} # 默认是空字典
print(type(s))
s = {1,2} # s = set({1,2})
定义空集合:
s = set()
print(s,type(s))
三:类型转换
set({1,2,3})
res = set('hellollll') # 可以去重
print(res)
{'e', 'o', 'h', 'l'}
print(set([1,1,1,1,1,1,1]))
{1}
print(set([1,1,1,1,1,1,1,[11,222]]))
TypeError: unhashable type: 'list'
print(set({'k1':1,'k2':2}))
{'k1', 'k2'}
四:内置方法
1.关系运算符
① 取出交集:两者共同的好友
friends1 = {"zero","kevin","jason","egon"} # 用户1的好友们
friends2 = {"Jy","ricky","jason","egon"} # 用户2的好友们
res = friends1 & friends2
res = friends1.intersection(friends2)
print(res)
{'egon', 'jason'}
② 取出并集/交集:两者所有的好友
friends1 = {"zero","kevin","jason","egon"} # 用户1的好友们
friends2 = {"Jy","ricky","jason","egon"} # 用户2的好友们
res = friends1 | friends2
res = friends1.union(friends2)
print(res)
{'egon', 'kevin', 'ricky', 'Jy', 'zero', 'jason'}
③ 取出差集:取出其中一个集合独有的好友
取出 friends1 独有的好友:
friends1 = {"zero","kevin","jason","egon"} # 用户1的好友们
friends2 = {"Jy","ricky","jason","egon"} # 用户2的好友们
res = friends1 - friends2
res = friends1.difference(friends2)
print(res)
{'kevin', 'zero'}
取出 friends2 独有的好友:
friends1 = {"zero","kevin","jason","egon"} # 用户1的好友们
friends2 = {"Jy","ricky","jason","egon"} # 用户2的好友们
res = friends2 - friends1
res = friends1.symmetric_difference(friends2)
print(res)
{'ricky', 'Jy'}
④ 对称差集:求2个用户独有的好友们(即:去掉共同的好友)
friends1 = {"zero","kevin","jason","egon"} # 用户1的好友们
friends2 = {"Jy","ricky","jason","egon"} # 用户2的好友们
res = friends2 ^ friends1
print(res)
{'kevin', 'Jy', 'ricky', 'zero'}
⑤ 父子集:包含的关系
s1 = {1,2,3}
s2 = {1,2,4}
# 不存在包含关系,下面比较均为False
print(s1.issupersets2())
print(s1 > s2)
print(s1 < s2)
s1 = {1,2,3}
s2 = {1,2}
print(s1.issubset(s2))
print(s1 > s2) # 当s1大于或等于s2时,才能说s1是s2的爹
s1={1,2,3}
s2={1,2,3}
print(s1 == s2) # s1与s2互为父子
2.去重
① 只能针对不可变类型去重
print(set([1,1,2,2,2]))
{1, 2}
② 无法保证原来的顺序
l = [1,'a','b',1,1,2,3]
l = list(set(l))
print(l)
[1, 2, 3, 'a', 'b']
3.长度
>>> s={'a','b','c'}
>>> len(s)
3
4.成员运算
>>> 'c' in s
True
5.循环
>>> for item in s:
... print(item)
...
c
a
b
五:其他内置方法
.discard() —— 需要掌握
s = {1,2,3}
s.discard(4) # 删除元素不存在,do nothing
print(s)
.remove()
s = {1,2,3}
s.remove(4) # 删除元素不存在,则会报错
print(s)
.update() —— 需要掌握
s = {1,2,3}
s.update({1,3,5})
.pop() —— 需要掌握
s = {1,2,3}
res = s.pop()
print(res)
.add() —— 需要掌握
s = {1,2,3}
s.add(4)
print(res)