集合是无序不可重复可变的,它相当于没有 key 的字典
创建一个集合
a={1,2,3}
b=set([1,2,3])
print(a,type(a))
print(b,type(b))
#输出
{1, 2, 3} <class 'set'>
{1, 2, 3} <class 'set'>
创建一个空集合
用set() 而不用{} 因{} 会被当成一个空字典
集合方法
添加元素
add() :一次添加一个元素
update(): 至少添加一个元素 ,参数为序列
xxx.update([999]) 正确
xxx.update(999) 报错
a={1,2,3}
print(a,id(a))
a.add(4)
print(a,type(a),id(a))
a.update([7,8,9])
print(a,type(a),id(a))
a.update({100,200,300})
print(a,type(a),id(a))
a.update("hello")
print(a,type(a),id(a))
#a.update(999)
#发生异常: TypeError
#'int' object is not iterable
#输出
{1, 2, 3} 1966296618816
{1, 2, 3, 4} <class 'set'> 1966296618816
{1, 2, 3, 4, 7, 8, 9} <class 'set'> 1966296618816
{1, 2, 3, 4, 100, 7, 8, 9, 200, 300} <class 'set'> 1966296618816
{1, 2, 3, 4, 100, 'e', 7, 8, 9, 200, 'h', 300, 'l', 'o'} <class 'set'> 1966296618816
删除元素
remove() 一次删除一个指定元素,如果元素不存在,则抛出KeyError
discard() 一次删除一个指定元素,如果不存在,不报异常
pop() 一次删除任意一个元素,无参数
clear() 清除集合内容
a={1,2,3,4,5,6}
a.remove(1)
print(a)
#a.remove(200) 报错
a.discard(500) #不存在不报错
a.discard(2) #有则删除
print(a)
a.pop() #随机删除一个元素
print(a)
#输出
{2, 3, 4, 5, 6}
{3, 4, 5, 6}
{4, 5, 6}