用途:用于关系运算的集合体,由于集合内的元素无序且集合元素不可重复,因此集合可以去重,但是去重后的集合会打乱原来元素的顺序。
定义方式:{}内用逗号隔开多个元素,元素只能是不可变类型(整形、浮点型字符串),且有两个特点:
1、会删除重复的值
2、会打乱集合内的值
wenyi_girlfriend_set = {'fanping', 'zhuping', 'qiangge', 'changyi', 'muzhiguniang1', 'muzhiguniang1','nick'}
zhuping_jiyou_set = {'fanping', 'wenynyi', 'qiange', 'wuzhiguniang'}
print(wenyi_girlfriend_set)
{'fanping', 'nick', 'muzhiguniang1', 'changyi', 'qiangge', 'zhuping'}
自定义set方法
wenyi_freind_list = ['ruhua','suiyue','suiyue']
print(set(wenyi_freind_list))
# def set(wenyi_freind_list):
# s = set()
# for i in wenyi_freind_list:
# s.add(i)
# print(s)
{'suiyue', 'ruhua'}
常用操作和内置方法
长度len
print(len(wenyi_girlfriend_set))
6
成员运算 in 和 not in
print('fanping'in wenyi_girlfriend_set)
True
并集 内置=.union 快捷符号=“|” (两个集合的汇总,必考)
print(wenyi_girlfriend_set.union(zhuping_jiyou_set))
print(wenyi_girlfriend_set | (zhuping_jiyou_set))
{'fanping', 'nick', 'wuzhiguniang', 'muzhiguniang1', 'wenynyi', 'changyi', 'qiange', 'qiangge', 'zhuping'}
{'fanping', 'nick', 'wuzhiguniang', 'muzhiguniang1', 'wenynyi', 'changyi', 'qiange', 'qiangge', 'zhuping'}
交集 内置=intersection 快捷符号=“&” (连个集合的共有的值,必考)
print(wenyi_girlfriend_set.intersection(zhuping_jiyou_set))
print(wenyi_girlfriend_set & (zhuping_jiyou_set))
{'fanping'}
{'fanping'}
差集 内置=difference 快捷符号=“-” (前面集合减去后面集合所剩的值)
print(wenyi_girlfriend_set.difference(zhuping_jiyou_set))
print(wenyi_girlfriend_set - (zhuping_jiyou_set))
{'nick', 'muzhiguniang1', 'changyi', 'qiangge', 'zhuping'}
{'nick', 'muzhiguniang1', 'changyi', 'qiangge', 'zhuping'}
对称差集 内置=symmetric_difference 快捷符号“^”(等于两个集合的汇总再减去两个集合共有的值)
print(wenyi_girlfriend_set.symmetric_difference(zhuping_jiyou_set))
print(wenyi_girlfriend_set ^ (zhuping_jiyou_set))
{'zhuping', 'nick', 'wenynyi', 'muzhiguniang1', 'changyi', 'qiange', 'qiangge', 'wuzhiguniang'}
{'zhuping', 'nick', 'wenynyi', 'muzhiguniang1', 'changyi', 'qiange', 'qiangge', 'wuzhiguniang'}
==
print(wenyi_girlfriend_set == zhuping_jiyou_set)
False
父集 >、>= 、issuperset (A包含B,A>B,则为true,否则为false)
print(wenyi_girlfriend_set > zhuping_jiyou_set)
print(wenyi_girlfriend_set.issuperset(zhuping_jiyou_set))
False
False
子集 < 、<= 、issubset
print(wenyi_girlfriend_set < zhuping_jiyou_set)
print(wenyi_girlfriend_set.issubset(zhuping_jiyou_set))
False
False
add 添加
s={1,2,'a'}
s.add(3)
print(s)
{3, 1, 2, 'a'}
remove 移除
s.remove(2)
print(s)
{3, 1, 'a'}
difference_update (从S1这个集合中删除另一个集合S2的所有元素。)
s1 = {1,2,3,'a'}
s2 = {1,2,'a'}
print(s1.difference_update(s2))
print(s1)
None
{3}
isdisjoint (如果两个集合的交集为空,则返回True。)
print(s1.isdisjoint(s2))
True