python集合

一、创建集合

创建集合使用{}或set(),但如果要创建空集合只能使用set(),因为{}用来创建空字典。

注意:集合中的数据不重复

  • 创建有数据的集合
s1 = {10, 29, 30, 49, 50}
print(f's1: {s1}')

s2 = {10, 39, 20, 40, 20, 10}
print(f's2: {s2}')

s3 = set('abcdefg')
print(f's3: {s3}')

image

  • 创建空集合
s4 = set()
print(f's4: {s4}')
print(type(s4))

s5 = {}
print(type(s5))

image

二、集合常见操作方法

2.1 增加数据

2.1.1 add()

s1 = {10, 20}

# add()
s1.add(100)
print(s1)

s1.add(100) # 集合有去重功能
print(s1)

# s1.add([10, 20, 30])    # 报错
# print(s1)

image

2.1.2 update():追加的数据是序列

s1 = {10, 20}

# update():增加的数据是序列
s1.update([10, 20, 30, 40, 50])
print(s1)

# s1.update(100)  # 报错
# print(s1)

image

2.2 删除数据

2.2.1 remove()

s1 = {10, 20, 30, 40, 50}

# remove(): 删除指定数据,如果数据不存在,报错
s1.remove(10)
print(s1)

s1.remove(10)   # 报错
print(s1)

image

2.2.2 discard()

s1 = {10, 20, 30, 40, 50}

# discard():删除指定数据,如果数据不存在,不报错
s1.discard(10)
print(s1)

s1.discard(10)  # 不报错
print(s1)

image

2.2.3 pop()

s1 = {10, 20, 30, 40, 50}

# pop():随机删除某个数据,并返回这个数据
del_num = s1.pop()
print(del_num)
print(s1)

image

2.3 查找数据

  • in:判断数据在集合序列
  • not in: 判断数据不在集合序列
s1 = {10, 20, 30, 40, 50}

# in , not in 判断数据10是否存在
print(10 in s1)		# True
print(10 not in s1)		# False
posted @ 2021-04-01 09:25  红尘梦一场  阅读(86)  评论(0编辑  收藏  举报