集合
1.集合的格式{数据1,数据2,数据3,...}
例:
s1 = {10,20,30,40}
print(type(s1)) #set类型
返回结果:
<class 'set'>
2.定义空集合,注意:只能用set()
s2 = set()
print(s2)
返回结果:
set()
3.集合的特点:无序和去重
s3 = {10,20,10,40,20}
print(s3) #集合中的数值不重复,去重
返回结果:
{40, 10, 20}
4.集合的常用操作
增加
集合名.add(数据)
:数据不能是序列,是序列就会报错(不报错字符串)
#例如:
s1 = {10,20}
s1.add(30)
print(s1)
返回结果:
{10, 20, 30}
#例如:
s1 = {10,20}
s1.add([12,13]) #报错
print(s1)
返回结果:
TypeError: unhashable type: 'list'
集合名.update(序列)
#例如:
s1 = {10,20}
s1.update([12,13]) #序列是逐一添加
print(s1)
返回结果:
{10, 13, 20, 12}
#例如:
s1 = {10,20}
s1.update(30) #报错,单个数据不能添加
print(s1)
返回结果:
TypeError: 'int' object is not iterable
删除
集合名.remove
:删除指定数据
#例如:
s2 = {10,20,30,40}
s2.remove(30) #{40, 10, 20},删除指定数据
print(s2)
返回结果:
{40, 10, 20}
#例如:
s2 = {10,20,30,40}
s2.remove(50) #删除不存在的数据会报错
print(s2)
返回结果:
KeyError: 50
集合名.discard()
:删除指定数据
#例如:
s2 = {10,20,30,40}
s2.discard(30) #{40, 10, 20},删除指定数据
print(s2)
返回结果:
{40, 10, 20}
#例如:
s2 = {10,20,30,40}
s2.discard(50) #删除不存在的数据,不会报错
print(s2)
返回结果:
{40, 10, 20, 30}
集合名.pop()
#例如:
s2 = {10,20,30,40}
del_num = s2.pop() #返回被删除的数据
print(del_num) #40,随机删除,因为集合的无序特点,默认删除集合中的第一个数据
print(s2)
返回结果:
40
{10, 20, 30}
查找:in 和 not in
s3 = {10,20,30,40}
#in:存在则返回True,不存在则返回False
print(30 in s3) #存在则返回True
print(50 in s3) #不存在则返回False
#not in:存在则返回False,不存在则返回True
print(30 not in s3) #存在则返回False
print(50 not in s3) #不存在则返回True
返回结果:
True
False
False
True