ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

集合

2022-08-27 23:01:25  阅读:183  来源: 互联网

标签:10 20 s2 s1 50 print 集合


1、创建集合

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

  特点:

    1. 集合可以去掉重复数据;

    2. 集合数据是无序的,故不支持下标。

s1 = {10, 20, 30, 40, 50}  # 无序
# 结果:{50, 20, 40, 10, 30}
print(s1)

s2 = {10, 20, 50, 90, 20, 50}  # 去掉重复
# 结果:{10, 50, 20, 90}
print(s2)

s3 = {'abcdefg'}
# 结果:{'abcdefg'}
print(s3)

s4 = set('abcdefgh')  # 拆分成单个
# 结果:{'a', 'e', 'f', 'g', 'b', 'c', 'h', 'd'}
print(s4)

s5 = set()  # 空集合 
# 结果:set()
print(s5)
# 结果:<class 'set'>
print(type(s5))

s6 = {}  # 空字典
# 结果:<class 'dict'>
print(type(s6))

2、集合常见操作方法

  2.1 增加数据

    add()增加单一数据,增加序列则会报错

 

s1 = {10, 20, 30}
s1.add(100)
# 结果:{100, 10, 20, 30}
print(s1)
s1.add(10)
# 结果:{100, 10, 20, 30}
print(s1)
s1.add([50, 60])
# 结果: 报错
print(s1)

 

    update()追加数据序列,增加单一数据则报错

 

s2 = {20, 50, 80}
s2.update([100, 200])
# 结果:{100, 200, 80, 50, 20}
print(s2)
s2.update('abc')
# 结果:{100, 200, 'b', 80, 'c', 50, 20, 'a'}
print(s2)
s2.update(30)
# 结果:报错
print(s2)

 

  2.2 删除数据

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

s1 = {10, 20, 40, 50, 60}
s1.remove(20)
# 结果:{50, 40, 10, 60}
print(s1)
s1.remove(20)
# 结果:报错
print(s1)

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

 

s1 = {10, 20, 40, 50, 60}
s1.discard(20)
# 结果:{50, 40, 10, 60}
print(s1)
s1.discard(20)
# 结果:{50, 40, 10, 60}
print(s1)

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

 

s1 = {10, 20, 40, 50, 60}
s1.pop()
# 结果:{20, 40, 10, 60}
print(s1)
s2 = s1.pop()
# 结果:20
print(s2)
# 结果:{40, 10, 60}
print(s1)

 

 

  2.3 查找数据

    in :判断数据在集合序列

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

 

s3 = {20, 50, 90}
# 结果:True
print(20 in s3)
# 结果:False
print(30 in s3)
# 结果:False
print(20 not in s3)
# 结果:True
print(400 not in s3)

 

标签:10,20,s2,s1,50,print,集合
来源: https://www.cnblogs.com/yz-b/p/16631723.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有