创建集合使用{}或set(),但是如果要创建空集合只能使用set(),因为{}用来创建字典。
集合会去重。集合里的数据没有顺序。
s2 = {10, 30, 20, 40, 30, 20}
print(s2) # {40, 10, 20, 30}
s3 = set('abcdefg')
print(s3) # {'a', 'b', 'c', 'f', 'd', 'g', 'e'}
s4 = set()
print(s4) # set()
print(type(s4)) # <class 'set'>
s5 = {}
print(type(s5)) # <class 'dict'>
二、集合常见操作方法
2.1 增加数据
add() 增加单一数据。
因为集合有去重功能,所以,当向集合内追加的数据是当前集合已有数据的放在,则不进行任何操作。
update(),追加的数据是序列。
s1 = {10, 20}
# 1. 集合是可变类型
# add() 增加单一数据
s1.add(100)
print(s1) # {100, 10, 20}
# 集合有去重功能,如果追加的数据是集合已有数据,则什么事情都不做。
s1.add(100)
print(s1) # {100, 10, 20}
# s1.add([10, 20, 30])
# print(s1)# TypeError: unhashable type: 'list' # 只能追加单一数据
# update() 增加序列
s1 = {10, 20}
s1.update([10, 20, 30, 40, 50])
print(s1) # {40, 10, 50, 20, 30}
# s1.update(100) # 报错
# print(s1) # TypeError: 'int' object is not iterable
2.2 删除数据
remove(),删除集合中的指定数据,如果数据不存在则报错。
discard(),删除集合中的指定数据,如果数据不存在也不会报错。
pop(),随机删除集合中的某个数据,并返回这个数据。
s1 = {10, 20, 30, 40, 50}
# remove() 删除集合中的指定数据,如果数据不存在则报错。
s1.remove(10)
print(s1) # {40, 50, 20, 30}
# s1.remove(10) # 10在前面已被删除而不存在,报错
# print(s1) # KeyError: 10
# discard() 删除集合中的指定数据,如果数据不存在也不会报错。
s1 = {10, 20, 30, 40, 50}
s1.discard(10)
print(s1) # {40, 50, 20, 30}
s1.discard(10)
print(s1) # {40, 50, 20, 30}
# pop() 随机删除集合中的某个数据,并返回这个数据。
del_num = s1.pop()
print(del_num) # 40
print(s1) # {50, 20, 30}
2.3 查找数据
in:判断数据在集合序列
not in:判断数据不在集合序列
s1 = {10, 20, 30, 40, 50}
# in 或 not in
print(10 in s1) # True
print(10 not in s1) # False