Python study notes (X) collection

Python study notes (X) collection

First, create a collection

Here Insert Picture Description

# 1. 创建有数据的集合
s1 = {10,20,30,40,50}
print(s1)
print(type(s1))

Here Insert Picture Description
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)

Here Insert Picture Description
set () can also create collections

# set()创建集合
s3 = set('abcdefg')
print(s3)

Here Insert Picture Description

# 2. 创建空集合只能用set()
s2 = set()
s4 = {}  #字典不是集合
print(type(s2))
print(type(s4))

Here Insert Picture Description

Second, a set of common methods of operation

2.1 increase data

Here Insert Picture Description
Additional single data.
Here Insert Picture Description
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:
Here Insert Picture Description

2.2 to delete data

Here Insert Picture Description

s1 = {10,20,30,40,50}
# 1. remove():删除指定数据,如果数据不存在会报错
s1.remove(10)
print(s1)
s1.remove(60)
print(s1)  #不存在,会报错

Here Insert Picture Description
Here Insert Picture Description

s1 = {10,20,30,40,50}
#  2. discard():删除指定数据,如果数据不存在不会会报错
s1.discard(10)
print(s1)
s1.discard(60)
print(s1)  #不报错

Here Insert Picture Description
Here Insert Picture Description

s1 = {10,20,30,40,50}
# 3. pop():随机删除数据,并返回该数据
del_num = s1.pop()
print(del_num)
print(s1)

Here Insert Picture Description

2.3 Finding Data

Here Insert Picture Description

s1 = {10,20,30,40,50}
# in
print(10 in s1)
#not in
print(60 not in s1)

Here Insert Picture Description

Third, the summary

Here Insert Picture Description
Here Insert Picture Description

Published 14 original articles · won praise 0 · Views 472

Guess you like

Origin blog.csdn.net/Ydn000/article/details/104228592