14、数据容器之集合

# 可以容纳多个数据
# 可以容纳不同类型的数据(混装)
# 数据是无序存储的(不支持下标索引)
# 不允许重复数据存在
# 可以修改(增加或删除元素等)
# 支持for循环

# 定义集合
my_set = {'传智教育','黑马程序员', 'itheima', '传智教育', '黑马程序员', 'itheima'}
my_set_empty = set()         # 定义空集合
print(f"my_set的内容是:{my_set},类型是{type(my_set)}")

# 添加元素 add
my_set.add('liujin666')
print(f"新集合的内容为{my_set}")

# 移除元素 remove
my_set.remove('liujin666')
print(f"新集合的内容为{my_set}")

# 从集合中随机取出一个元素 pop
element = my_set.pop()
print(f"取出来的新元素是:{element}")

# 清空集合 clear
# my_set.clear()
# print(my_set)

# 取两个集合的差集
set1 = {1, 2, 3, 4, 5, 6}
set2 = {1, 2, 7, 8, 9, 10}
set3 = set1.difference(set2)    # 集合1有而集合2没有的
print(set1)
print(set2)
print(f"取set1和set2中的差集{set3}")

# 消除2个集合的相同元素
set1.difference_update(set2)           # 对比集合1、2,在集合1内删除和集合2中相同的元素,集合1发生变化、集合2不变
print(f"给集合1去差集之后集合1为{set1},集合2的内容为{set2}")

# 将两个集合合并为1个
set1 = {1, 2, 3, 4, 5, 6}
set2 = {1, 2, 7, 8, 9, 10}
set3 = set1.union(set2)
print(f"将set1和set2合并的集合内容为:{set3}")

# 统计几何元素数量
num = len(set3)
print(f"集合3中元素的个数为:{set3}")

# 集合的遍历
# ***********while循环不可以,因为集合无序,不可访问下标
# for循环ok
print('**********for循环遍历************')
for i in set3:
    print(f"set3的内容有{i}")

# ********practice********************************************************
my_list = ['黑马程序员', '传智播客', '黑马程序员', '传智播客', 'itheima', 'itcast', 'itheima', 'itcast', 'best']
my_set_1 = set()
for i in my_list:
    my_set_1.add(i)
print(my_set_1)

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值