[Python 基础课程]Set
Set
集合(set)是一种无序的不重复元素序列。说简单点,就是元素不能重复的列表。
创建
第一种创建方法是使用花括号 {}
: 将元素直接放在花括号中,每个元素之间用逗号 ,
分隔。
my_set = {1, 2, 3}
# {1, 2, 3}
print(my_set)
:::warning
创建空集合不能使用 {}
,因为 {}
会创建一个空字典。要创建空集合,你需要使用 set()
函数。
:::
使用 set()
函数: 可以将其他可迭代对象(如列表、元组、字符串等)转换为集合。set()
函数会自动去除重复的元素。
my_list = [1, 2, 2, 3, 4, 4, 5]
my_set_from_list = set(my_list)
# 输出: {1, 2, 3, 4, 5}
print(my_set_from_list)my_tuple = (3, 4, 5, 5, 6)
my_set_from_tuple = set(my_tuple)
# 输出: {3, 4, 5, 6}
print(my_set_from_tuple)my_string = "hello"
my_set_from_string = set(my_string)
# 输出: {'h', 'e', 'l', 'o'}
print(my_set_from_string)
集合的基本操作
添加元素
使用 add()
方法向集合中添加单个元素。
my_set = {1, 2, 3}
my_set.add(4)
# 输出: {1, 2, 3, 4}
print(my_set)# 添加已存在的元素,集合不会改变
my_set.add(3)
# 输出: {1, 2, 3, 4}
print(my_set)
使用 update()
方法可以一次性添加多个元素,参数可以是列表、元组或其他集合。
my_set = {1, 2}
my_set.update([3, 4, 4])
# 输出: {1, 2, 3, 4}
print(my_set)another_set = {5, 6}
my_set.update(another_set)
# 输出: {1, 2, 3, 4, 5, 6}
print(my_set)
移除元素
有两种常用的方法可以移除集合中的元素。
remove(element)
: 移除指定的元素。如果元素不存在,会抛出 KeyError
错误。
my_set = {1, 2, 3}
my_set.remove(2)
# 输出: {1, 3}
print(my_set)# 这会抛出 KeyError: 4
# my_set.remove(4)
discard(element)
: 移除指定的元素。如果元素不存在,不会抛出错误。
my_set = {1, 2, 3}
my_set.discard(2)
# 输出: {1, 3}
print(my_set)# 元素不存在,不会有任何影响
my_set.discard(4)
# 输出: {1, 3}
print(my_set)
pop()
方法可以随机移除集合中的一个元素,并返回被移除的元素。由于集合是无序的,你无法预测哪个元素会被移除。如果集合为空,调用 pop()
会抛出 KeyError
。
my_set = {1, 2, 3}
removed_element = my_set.pop()
# 输出可能是 1, 2 或 3
print(removed_element)
# 输出会少一个元素
print(my_set)
清空集合
clear()
方法会移除集合中的所有元素,使其变成一个空集合。
my_set = {1, 2, 3}
my_set.clear()
# 输出: set()
print(my_set)
判断元素是否在集合中
使用 in
关键字可以快速判断一个元素是否在集合中。
my_set = {1, 2, 3}
# 输出: True
print(2 in my_set)
# 输出: False
print(4 in my_set)
获取集合的长度
使用 len()
函数可以获取集合中元素的个数。
my_set = {1, 2, 3, 4}
# 输出: 4
print(len(my_set))
集合的运算
并集(Union):返回包含两个集合所有元素的的新集合。可以使用 |
运算符或 union()
方法。
set1 = {1, 2, 3}
set2 = {3, 4, 5}union_set1 = set1 | set2
# 输出: {1, 2, 3, 4, 5}
print(union_set1)union_set2 = set1.union(set2)
# 输出: {1, 2, 3, 4, 5}
print(union_set2)
交集(Intersection): 返回包含两个集合共有元素的新集合。可以使用 &
运算符或 intersection()
方法。
set1 = {1, 2, 3}
set2 = {3, 4, 5}intersection_set1 = set1 & set2
# 输出: {3}
print(intersection_set1)intersection_set2 = set1.intersection(set2)
# 输出: {3}
print(intersection_set2)
差集(Difference): 返回包含第一个集合中存在,但第二个集合中不存在的元素的新集合。可以使用 -
运算符或 difference()
方法。
set1 = {1, 2, 3}
set2 = {3, 4, 5}difference_set1 = set1 - set2
# 输出: {1, 2}
print(difference_set1)difference_set2 = set1.difference(set2)
# 输出: {1, 2}
print(difference_set2)difference_set3 = set2 - set1
# 输出: {4, 5}
print(difference_set3)
对称差集(Symmetric Difference):返回包含两个集合中不重复出现的所有元素的新集合。可以使用 ^
运算符或 symmetric_difference()
方法。
set1 = {1, 2, 3}
set2 = {3, 4, 5}symmetric_difference_set1 = set1 ^ set2
# 输出: {1, 2, 4, 5}
print(symmetric_difference_set1)symmetric_difference_set2 = set1.symmetric_difference(set2)
# 输出: {1, 2, 4, 5}
print(symmetric_difference_set2)