自学内容网 自学内容网

07_Python数据类型_集合

在这里插入图片描述

Python的基础数据类型

  • 数值类型:整数、浮点数、复数、布尔
  • 字符串
  • 容器类型:列表、元祖、字典、集合

集合

集合(set)是Python中一个非常强大的数据类型,它存储的是一组无序且不重复的元素,集合中的元素必须是不可变的,且元素之间用逗号隔开,集合的元素之间用大括号括起来。集合是可变数据类型。

集合的特点:

  • 确定性:集合中的元素是不可变类型。集合是可变数据类型。
  • 互异性:集合中的元素互不相同,不能重复,元素是唯一的。
  • 无序性:集合中的元素无序,即不能通过索引访问集合中的元素。只能遍历。

定义集合

可以使用大括号 {} 或者 set() 函数来创建集合。如果使用大括号,则至少需要包含一个元素;如果使用 set(),则可以创建一个空集合。

# 创建一个空集合
empty_set = set()
# 创建一个包含一个元素的集合
single_element_set = {1}
# 创建一个包含几个元素的集合
my_set = {1, 2, 3, 'a', 'b', 'c'}

访问集合元素

由于集合是无序的,因此不能通过索引来访问元素。但是,可以使用循环来遍历集合中的所有元素。

# 遍历集合
for element in my_set:
    print(element)

集合操作

集合支持多种操作,如并集、交集、差集等。

  • 并集(Union):使用 | 运算符或 union() 方法。
  • 交集(Intersection):使用 & 运算符或 intersection() 方法。
  • 差集(Difference):使用 - 运算符或 difference() 方法。
  • 对称差集(Symmetric Difference):使用 ^ 运算符或 symmetric_difference() 方法。
# 定义两个集合
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}

# 并集
union_set = set1 | set2  # 或 set1.union(set2)
union_set1 = set1.union(set2)
print(union_set)
print(union_set1)
# 交集
intersection_set = set1 & set2  # 或 set1.intersection(set2)
intersection_set1 = set1.intersection(set2)
print(intersection_set)
print(intersection_set1)
# 差集
difference_set = set1 - set2  # 或 set1.difference(set2)
difference_set1 = set1.difference(set2)
print(difference_set)
print(difference_set1)
# 对称差集
symmetric_difference_set = set1 ^ set2  # 或 set1.symmetric_difference(set2)
symmetric_difference_set1 = set1.symmetric_difference(set2)
print(symmetric_difference_set)
print(symmetric_difference_set1)

集合方法

集合还提供了许多有用的方法,如:

  • add():向集合中添加一个元素。
  • remove():从集合中移除一个元素,如果元素不存在,则抛出 KeyError。
  • discard():从集合中移除一个元素,如果元素不存在,则什么也不做。
  • pop():随机移除并返回集合中的一个元素。
  • clear():清空集合中的所有元素。
# 向集合中添加元素
my_set.add('d')
print(my_set)

# 从集合中移除元素
my_set.remove('a')
print(my_set)

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

集合推导式

与列表推导式类似,集合推导式可以用来生成集合。

# 创建一个包含0-9每个数字的平方的集合
squared_set = {x**2 for x in range(10)}
print(squared_set)
# 列表推导式
s = {8, 3, 1, 5, 11}
{i * 2 for i in s}

集合在Python中是一种非常有用的数据类型,特别是在需要快速检查元素是否存在或执行集合运算时。

附件

本文对应的jupyter notebook源码链接,欢迎下载练习:https://download.csdn.net/download/fx_yzjy101/89760705

如有问题请留言。


原文地址:https://blog.csdn.net/fx_yzjy101/article/details/142307479

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!