在 Python 中,集合(Set)是一种数据类型,类似于列表和元组,但集合中的元素是无序的且不重复的。集合可以通过花括号 {}
来创建,每个元素之间使用逗号分隔。
- 无序性:集合中的元素没有顺序。
- 唯一性:集合中的元素是唯一的,不会出现重复。
- 可变性:集合是可变的,可以向集合添加或删除元素。
- 支持多种数据类型:集合中可以包含不同类型的元素。
# 创建一个集合
my_set = {1, 'string', 's', [1, 2]}
# 添加元素到集合
my_set.add(5)
# 从集合中删除元素
my_set.remove(3)
# 检查元素是否存在于集合中
is_present = 2 in my_set# is_present是True or False
# 遍历集合中的元素
for item in my_set:
print(item)
在 Python 中,集合提供了并集、交集和差集等操作,这些操作可以用来组合和比较集合中的元素。
- 并集(Union):将两个集合的所有元素合并为一个新的集合,其中不包含重复元素。在 Python 中,可以使用
union()
方法或者|
运算符来获得两个集合的并集。
set1 = {1, 2, 3}
set2 = {3, 4, 5}
# 使用union()方法获取并集
union_set = set1.union(set2)
# 使用 | 运算符获取并集
union_set = set1 | set2
print(union_set) # Output: {1, 2, 3, 4, 5}
- 交集(Intersection):获取两个集合中共同存在的元素,形成一个新的集合。在 Python 中,可以使用
intersection()
方法或者&
运算符来获得两个集合的交集。
set1 = {1, 2, 3}
set2 = {3, 4, 5}
# 使用intersection()方法获取交集
intersection_set = set1.intersection(set2)
# 使用 & 运算符获取交集
intersection_set = set1 & set2
print(intersection_set) # Output: {3}
- 差集(Difference):获取一个集合中存在而另一个集合中不存在的元素,形成一个新的集合。在 Python 中,可以使用
difference()
方法或者-
运算符来获得两个集合的差集。
set1 = {1, 2, 3}
set2 = {3, 4, 5}
# 使用difference()方法获取差集
difference_set = set1.difference(set2)
# 使用 - 运算符获取差集
difference_set = set1 - set2
print(difference_set) # Output: {1, 2}