c++ set 删除子集_Python基础数据类型「set」

集合set

  • 集合是无序的,不重复的数据集合,它里面的元素是可哈希的(不可变类型),但是集合本身是不可哈希(所以集合做不了字典的键)的。以下是集合最重要的两点:
    • 去重,把一个列表变成集合,就自动去重了。
    • 关系测试,测试两组数据之前的交集、差集、并集等关系。

集合set创建

# The first methodcraete_set = {1, 2, 3, (1, 2, 3)}print(craete_set, type(craete_set))# The second methodsecond_set = set({1, 2, 3, 6})print(second_set, type(second_set))

集合set新增

set1 = {'run1','run2','run3','run4'}set1.add('run5')print(set1)# update:迭代着增加set1.update('A')print(set1)set1.update('my')print(set1)set1.update([1,2,3])print(set1)

集合set删除

set1 = {'run1','run2','run3','run4'}set1.remove('run1')  # 删除一个元素print("删除一个元素: ", set1)set1.pop()  # 随机删除一个元素print("随机删除一个元素: ", set1)set1.clear()  # 清空集合print("清空集合: ", set1)del set1  # 删除集合print("删除集合: ", set1)

集合set的其它操作

交集(& 或者 intersection)

set1 = {1,2,3,4,5}set2 = {4,5,6,7,8}print(set1 & set2)  # {4, 5}print(set1.intersection(set2))  # {4, 5}

并集(| 或者 union)

set3 = {1,2,3,4,5}set4 = {4,5,6,7,8}print(set3 | set4)  # {1, 2, 3, 4, 5, 6, 7}print(set3.union(set4))  # {1, 2, 3, 4, 5, 6, 7}

差集(- 或者 difference)

set5 = {1,2,3,4,5}set6 = {4,5,6,7,8}print(set5 - set6)  # {1, 2, 3}print(set5.difference(set6))  # {1, 2, 3}

反交集(^ 或者 symmetric_difference)

set7 = {1,2,3,4,5}set8 = {4,5,6,7,8}print(set7 ^ set8)  # {1, 2, 3, 6, 7, 8}print(set7.symmetric_difference(set8))  # {1, 2, 3, 6, 7, 8}

子集与超集

set9 = {1,2,3}set0 = {1,2,3,4,5,6}print(set9 < set0)print(set9.issubset(set0))  # 这两个相同,都是说明set9是set0子集。print(set0 > set9)print(set0.issuperset(set9))  # 这两个相同,都是说明set0是set0超集。

PS: frozenset不可变集合,让集合变成不可变类型

s = frozenset('barry')print(s,type(s))  # frozenset({'a', 'y', 'b', 'r'}) 
f3267e1cb7f27850a86581780544ab07.png

#Python##python打卡##笨办法学Python 3#

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值