Python study notes (X) collection
First, create a collection
# 1. 创建有数据的集合
s1 = {10,20,30,40,50}
print(s1)
print(type(s1))
NOTE: The result can be seen that the output sequence is not set. Therefore, it does not support index action, and does not allow duplicate set of data is present, a set of data having a deduplication function.
s1 = {10,20,30,40,50,50}
print(s1)
set () can also create collections
# set()创建集合
s3 = set('abcdefg')
print(s3)
# 2. 创建空集合只能用set()
s2 = set()
s4 = {} #字典不是集合
print(type(s2))
print(type(s4))
Second, a set of common methods of operation
2.1 increase data
Additional single data.
Additional data sequence.
example:
s1 = {10,20}
# 1. add():用来增加单一数据
s1.add(40)
print(s1) #集合是可变类型
s1.add(20)
print(s1) #集合有去重功能,如果追加的数据是集合已有的数据,则什么也不变
s2 = {10,20}
# 2. update():用来增加序列
s2.update([20,30,40,50])
print(s2)
Screenshot results:
2.2 to delete data
s1 = {10,20,30,40,50}
# 1. remove():删除指定数据,如果数据不存在会报错
s1.remove(10)
print(s1)
s1.remove(60)
print(s1) #不存在,会报错
s1 = {10,20,30,40,50}
# 2. discard():删除指定数据,如果数据不存在不会会报错
s1.discard(10)
print(s1)
s1.discard(60)
print(s1) #不报错
s1 = {10,20,30,40,50}
# 3. pop():随机删除数据,并返回该数据
del_num = s1.pop()
print(del_num)
print(s1)
2.3 Finding Data
s1 = {10,20,30,40,50}
# in
print(10 in s1)
#not in
print(60 not in s1)
Third, the summary