python笔记之序列(set的基本使用和常用操作)

集合(set)

集合(set):无序的,可变的,可包含任意对象的集合 ,每次输出的结果顺序都是不同的

特点:
1. 属于可变序列
2. 可以包含任意类型
3. 可变长度,任意嵌套
4. 支持原位改变
5. 集合不允许有重复的对象(相当于自动去重)

定义集合
student_set = {"xiao_a","xiao_b","xiao_c","xiao_c"}
print(type(student_set))
print(student_set)  

运行结果:

<class 'set'>
{'xiao_a', 'xiao_c', 'xiao_b'}
集合对列表去重
id_list = ["id1","id2","id1","id2"]
id_set = set(id_list)
print(id_set)

运行结果:

{'id2', 'id1'}
集合对字符串去重
string = "the one !!!"
print(string)
set =set(string)
print(set)

运行结果:

the one !!!
{'t', 'h', 'o', '!', ' ', 'e', 'n'}
定义一个空的集合

none_dict = {} #这里是创建一个空的字典
none_set = set() #空集合

集合的添加
name_set = {"wangzhe"}
name_set.add("rongyao")
print(name_set)

运行结果:

{'rongyao', 'wangzhe'}
.update 添加(序列)
name_set = {"wangzhe"}
name_set.update(["蓝天","白云"],["青山""绿水"])
print(name_set)

运行结果:

{'蓝天', '青山绿水', '白云', 'wangzhe'}
删除.remove()

删除一个不存在的元素会报错

name_set = {"wangzhe"}
name_set.remove("蓝天1")
print(name_set)

运行结果:

Traceback (most recent call last):
  File "G:/PyCharm_/python_basic/day01/first.py", line 2, in <module>
    name_set.remove("蓝天1")
KeyError: '蓝天1'
删除 .discard()

删除一个不存在的元素,不会报错

name_set = {"wangzhe"}
name_set.discard("蓝天1")

运行结果:

删除 .pop()

随机删除集合中的某个元素,并返回被删除的元素

p_set = {"1","2","3","4","5"}
print(p_set)
result = p_set.pop()
print(result)
print(p_set)

运行结果:

{'3', '4', '5', '1', '2'}
3
{'4', '5', '1', '2'}

如果是一个有序的集合比如1,2,3,4,5会从第一个开始依此删除

p_set1 = {1,2,3,4,5,6,7}
print(p_set1)
print(p_set1.pop())
print(p_set1.pop())
print(p_set1.pop())
print(p_set1)

运行结果:

{1, 2, 3, 4, 5, 6, 7}
1
2
3
{4, 5, 6, 7}
交集,并集,差集,对称差集
#交集   显示重复的
num_set1 = {1,2,3,4,6}
num_set2 = {5,2,3,4,6}

inter_set1 = num_set1 & num_set2
inter_set2 = num_set1.intersection(num_set2)
print(inter_set1)
print(inter_set2)

#并集:两个合并在一起
union_set1 = num_set1 | num_set2
union_set2 = num_set1.union(num_set2 )
print(union_set1)
print(union_set2)

#差集 (那些不是共有的)a里面有的 b里面没有
diff_set1 = num_set1 - num_set2
diff_set2 = num_set1.difference(num_set2)
print(diff_set1)
print(diff_set2)

#对称差集 (两个集合都存在的去除,然后合并)
sym_diff_set1 = num_set1^num_set2
sym_diff_set2 = num_set1.symmetric_difference(num_set2)
print(sym_diff_set1)
print(sym_diff_set2)

运行结果:

{2, 3, 4, 6}
{2, 3, 4, 6}
{1, 2, 3, 4, 5, 6}
{1, 2, 3, 4, 5, 6}
{1}
{1}
{1, 5}
{1, 5}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值