Python基础-集合

创建集合

集合数据特点

集合常见操作

一、创建集合

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

集合数据特点:去重、无序,因为是无序的,集合不支持下标操作

# 1、有数据集合
s1 = {10, 20, 30, 40, 50}
print(s1)
# 输出 {40, 10, 50, 20, 30}
s2 = {10, 10, 30, 40, 50, 40}
print(s2)
# 输出 {40, 10, 50, 30}
s3 = set()
print(type(s3))
# 输出 <class 'set'>
s4 = {}
print(type(s4))
# 输出 <class 'dict'>
s5 = set('abcedf')
print(s5)
# 输出 {'c', 'f', 'a', 'b', 'e', 'd'}

二、集合常见操作

2.1增加数据

add(),增加的是单一数据,集合有去重功能,所以,当向集合追加的数据是当前集合已有数据的话,则不进行任何操作。

# add()
s1 = {10, 20}
s1.add(10)
s1.add(100)
print(s1)
# 输出 {100, 10, 20}

update(),增加的是一个序列

# update()
s2 = {10, 20}
s2.update([10, 20, 30, 50, 60])
s2.update('sad')
print(s2)
# 输出 {'d', 10, 's', 50, 20, 'a', 60, 30}

2.2删除数据

remove(),删除集合中的指定数据,如果数据不存在则报错

# remove
s1 = {10, 20}
s1.remove(10)
print(s1)
# 输出 {20}
s1.remove(45)
# 输出 报错

discard(),删除集合中的指定数据,如果数据不存在也不会报错

# discard()
s2 = {30, 40}
s2.discard(30)
print(s2)
s2.discard(454)
print(s2)

pop()随机删除集合中的某个数据,并返回这个数据

#pop()
s3 = {50, 60, 70, 80}
s3.pop()
print(s3)
# 输出 {50, 60, 70}

2.3查找数据

in: 判断数据在集合序列

not in: 判断数据不在集合序列

s1 = {10, 20, 30, 40}
print(10 in s1)
# 输出 True
print(22 in s1)
# 输出 False
print(10 not in s1)
# 输出False
print(100 not in s1)
# 输出True

总结:

创建集合:

有数据集合:

s1 = {数据1, 数据2, 数据3}

无数据集合:

s1 = set() ., 不能用{},因为字典的空用了这个了

常见操作:

增加数据:

add() 增加单个数据

update() 增加序列数据

删除数据:

remove() 删除不存在的时候,报错

discard() 删除不存在的数据,不报错

pop() 随机删除集合中的某个数据

查找数据:

in 

not in

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

NeilNiu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值