
集合可以进行增删改操作
集合的创建方式

?
#集合的创建方式
#第一种创建方式使用{}
j={2, 2, 2, 3, 3, 3, 4, 5, 6, 6, 7, 9}#集合中的元素不允许重复
print(j)
#第二种创建方式
a=set(range(6))
print(a)
b=set([1, 2, 3, 3, 3, 4, 4, 5, 6, 7, 8])
print(b, type(b))
c=set((1, 2, 2, 3, 4, 4, 4, 5, 5, 6, 7, 8, 9, 0, 9))#集合中的元素是无序的
print(c, type(c))
d=set('studying python')
print(d, type(d))
e=set({2, 3, 4, 6, 6, 66, 89, 8, 99, 55, 5, 5, 4, 4, 3, 3})
print(e, type(e))
#定义一个空集合
a={}#dict字典类型
print(type(a))
r=set()
print(type(r))
?集合的相关操作
?
?集合的判断操作
?
#集合的相关操作
#集合的判断操做
a={10, 20, 30, 40, 50, 60, 66, 888, 999, 666}
print(10 in a)#Ture
print(333 in a)
print(666 not in a)
print(886 not in a)
?集合元素的新增操作
#集合元素的添加操作
b={10, 20, 30, 40, 50, 60, 66, 888, 999, 666}
b.add(90)#一次添加一个元素
print(b)
b.update({111, 222, 333})
print(b)
b.update([1, 2, 3])
b.update((6, 7, 8))
print(b)
?集合的删除操作

#集合的删除操作
b.remove(10)#一次删除一个指定元素,如果指定元素不存在抛出
b.remove(13)#KeyError: 13
print(b)
b.discard(333)#一次删除一个元素,如果指定元素不存在不抛出
b.discard(33)
print(b)
b.pop()#任意删除一个元素不能指定
?集合之间的关系

?
#相等判断
a={3, 4, 4, 5, 6, 7, 8}
b={1, 2, 3, 3, 6, 7, 8}
print(a==b)
print(a!=b)
#一个集合是否是另一个集合的子集
c1={1, 2, 3, 4, 5, 6}
c2={1, 2, 3, 4}
c3={1, 2, 9}
print(c2.issubset(c1))#T
print(c3.issubset(c1))#F
#一个集合是另一个集合的超集
print(c1.issuperset(c2))
print(c2.issuperset(c3))
#两个集合是否有交集
print(c2.isdisjoint(c3))#F有交集
c4={10, 20, 30}
print(c2.isdisjoint(c4))#B没有交集为T
?集合的数学操作
?
?
#交集
a={1, 2, 3, 4}
b={2, 3, 4, 5, 6}
print(a.intersection)
print(a & b)
#并集操作
print(a.union(b))
print(a| b)
print(a)
print(b)
#差集操作
print(a.difference(b))
print(a-b)
print(a)
print(b)
#对称差集
print(a.symmetric_difference(b))
print(a^b)

?
|