集合(set
)是一种无序、不可重复的数据类型,它非常适合用于存储唯一的元素并进行集合运算(如交集、并集、差集等)。集合是一个无序的数据结构,因此无法通过索引来访问集合中的元素。
# 使用 set() 函数创建空集合
empty_set = set()
# 使用大括号创建集合
my_set = {1, 2, 3, 4}
print(my_set) # 输出 {1, 2, 3, 4}
与列表的区别:
与字典的区别:
add()
:向集合中添加一个元素。如果元素已存在,集合不会重复添加。
my_set = {1, 2, 3}
my_set.add(4)
print(my_set) # 输出 {1, 2, 3, 4}
remove()
:从集合中删除指定元素。如果元素不存在,会抛出 KeyError
异常。
my_set = {1, 2, 3}
my_set.remove(2)
print(my_set) # 输出 {1, 3}
discard()
:从集合中删除指定元素。如果元素不存在,什么也不做,不会抛出异常。
my_set = {1, 2, 3}
my_set.discard(2)
my_set.discard(4) # 4 不存在,什么也不做
print(my_set) # 输出 {1, 3}
pop()
:删除并返回集合中的一个元素。由于集合是无序的,删除的元素是不确定的。
my_set = {1, 2, 3}
popped_element = my_set.pop()
print(popped_element) # 输出一个集合中的元素,例如 1
print(my_set) # 输出删除元素后的集合,例如 {2, 3}
clear()
:删除集合中的所有元素,使集合变为空集合。
my_set = {1, 2, 3}
my_set.clear()
print(my_set) # 输出 set()
copy()
:返回集合的一个浅拷贝。
my_set = {1, 2, 3}
new_set = my_set.copy()
print(new_set) # 输出 {1, 2, 3}
union()
或 |
:返回两个集合的并集,即包含所有不同元素的集合。
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)
print(union_set) # 输出 {1, 2, 3, 4, 5}
# 使用 | 运算符
union_set = set1 | set2
print(union_set) # 输出 {1, 2, 3, 4, 5}
intersection()
或 &
:返回两个集合的交集,即两个集合中都存在的元素。
set1 = {1, 2, 3}
set2 = {3, 4, 5}
intersection_set = set1.intersection(set2)
print(intersection_set) # 输出 {3}
# 使用 & 运算符
intersection_set = set1 & set2
print(intersection_set) # 输出 {3}
difference()
或 -
:返回两个集合的差集,即存在于第一个集合中但不在第二个集合中的元素。
set1 = {1, 2, 3}
set2 = {3, 4, 5}
difference_set = set1.difference(set2)
print(difference_set) # 输出 {1, 2}
# 使用 - 运算符
difference_set = set1 - set2
print(difference_set) # 输出 {1, 2}
symmetric_difference()
或 ^
:返回两个集合的对称差集,即只存在于其中一个集合中的元素。
set1 = {1, 2, 3}
set2 = {3, 4, 5}
symmetric_difference_set = set1.symmetric_difference(set2)
print(symmetric_difference_set) # 输出 {1, 2, 4, 5}
# 使用 ^ 运算符
symmetric_difference_set = set1 ^ set2
print(symmetric_difference_set) # 输出 {1, 2, 4, 5}