python-集合的方法

集合的方法

1.set.add()
set1 = {'a','b',1,2}
set1.add(3)
print(set1)
2.set.copy()

复制的是值,不是地址

set2=  set1.copy()
set2
3.set.clear()
set1.clear()
print(set1)
print(set2)
4.x.difference(y)

集合的差集 ,我们可用来 做 数据的不同数据的 处理

x = {'a','b','c',1,2,3}
y = {'a',1,'d'}
print( x.difference(y) )
5.x.difference_update(y)

求集合的差集,返回的新值 会覆盖 x

print(x.difference_update(y))
print(x)
6.set.discard()

删除 set中的元素,删除的不存在的话 ,不报错

set3 = {'a','b',3,4}
set3.discard('a')
set3.discard('c')
print(set3)
7.set.remove()

删除不存在的会报错

set3.remove(4)
# set3.remove(5)
print(set3)
7.set.remove()

删除不存在的会报错

set3.remove(4)
# set3.remove(5)
print(set3)
8.set.pop()

在运行效果中,pop() 是删除最后一个。可是为什么说是删除随机元素, 因为 set,是无序的 ,你不知道最后一个到底是谁,所以在一定程度上也可以说是删除随机的

set3.pop()
print(set3)
9.x.intersection(y)

返回两个集合的交集

x = {'a','b','c',1,2,3}
y = {1,'a'}
print( x.intersection(y) )
10.x.intersection_update(y)

返回两个集合的交集,并覆盖 x

x = {'a','b','c',1,2,3}
y = {1,'a'}
print(x.intersection_update(y))
print(x)
11.x.isdisjoint(y)

如果 x 与 y 有相同的则返回 False ,没有相同的则返回 True,或者 说成 x y 是否不一样

x = {'a','b','c',1,2,3}
y = {1,'a'}
print( x.isdisjoint(y) )
13.x.issuperset(y)

判断 y 中的所有是否都在 x 中。

x = {'a','b','c',1,2,3}
y = {1,'a'}
print( x.issuperset(y))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值