Python-集合

一、集合的特性

1、集合是无序的,不能通过下标进行索引

2、集合有天生去重的功能

 

二、集合的运算

set1 = {1, 2, 3, 4, 5}
set2 = {5, 6, 7, 8, 9}
set_union = set1.union(set2) #并集,将set2合并到set1,并去掉重复元素
set_union1 = set1 | set2
set_intersection = set1.intersection(set2) #交集
set_intersection1 = set1 & set2
set_diff = set1.difference(set2) #差集
set_diff1 = set1 - set2
print('set1和set2的并集为: ', set_union)
print('set1 | set2 = ', set_union1)
print('set1和set2的交集为: ', set_intersection)
print('set1 & set2 = ', set_intersection1)
print('set1和set2的差集为: ', set_diff)
print('set1 - set2 = ', set_diff1)

 

查看结果:

set1和set2的并集为:  {1, 2, 3, 4, 5, 6, 7, 8, 9}
set1 | set2 =  {1, 2, 3, 4, 5, 6, 7, 8, 9}
set1和set2的交集为:  {5}
set1 & set2 =  {5}
set1和set2的差集为:  {1, 2, 3, 4}
set1 - set2 =  {1, 2, 3, 4}

 

三、集合的其他方法

set1 = set() #set()初始化集合, set1= {}初始化为字典
set1 = {1,2,3,4,5}
set2 = {3,4}
bool1 = set1.issubset(set2)  #判断set1是否为set2的子集
bool2 = set1.issuperset(set2) #判断set1是否为set2的父集
bool3 = set1.isdisjoint(set2) #判断是否有交集,没有交集返回True

set1 = {1,2,3,4,5}
set1.add(6) #添加元素
set1.remove(1) #删除指定元素
set1.pop() #随机删除一个元素
set1.discard(4) #删除指定元素

 

转载于:https://www.cnblogs.com/jessicaxu/p/7684070.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值