# 可以容纳多个数据
# 可以容纳不同类型的数据(混装)
# 数据是无序存储的(不支持下标索引)
# 不允许重复数据存在
# 可以修改(增加或删除元素等)
# 支持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)
14、数据容器之集合
最新推荐文章于 2024-07-16 19:26:54 发布