集合(Set)
创建集合
使用花括号
{}
(注意:空集合不能用{}
)
# 创建包含元素的集合
my_set = {1, 2, 3, 'hello', (4, 5)}
print(my_set) # 输出顺序可能与输入不同,例如 {1, 2, 3, (4, 5), 'hello'}
# 创建空集合
empty_set = set()
print(type(empty_set)) # <class 'set'>
print(empty_set) # set()
使用
set()
构造函数:
# 从字符串创建 (字符去重)
char_set = set("hello")
print(char_set) # {'l', 'o', 'e', 'h'} 或类似顺序
# 从列表创建 (元素去重)
list_set = set([1, 2, 2, 3, 3, 3])
print(list_set) # {1, 2, 3}
# 从元组创建
tuple_set = set((1, 2, 3))
print(tuple_set) # {1, 2, 3}
# 创建空集合
empty_set = set()
基本操作
添加元素
my_set = {1, 2, 3}
my_set.add(4)
print(my_set) # {1, 2, 3, 4}
my_set.add(2) # 重复元素,无变化
print(my_set) # {1, 2, 3, 4}
删除元素:
remove(element)
:删除指定元素,如果元素不存在,会抛出 KeyError 异常
my_set = {1, 2, 3}
my_set.remove(2)
print(my_set) # {1, 3}
# my_set.remove(5) # KeyError!
discard(element)
: 删除指定元素。如果元素不存在,不会抛出异常,静默处理。
my_set = {1, 2, 3}
my_set.discard(2)
print(my_set) # {1, 3}
my_set.discard(5) # 无错误
print(my_set) # {1, 3}
pop()
: 随机移除并返回集合中的一个元素。因为集合无序,所以无法预测移除哪个元素。 如果集合为空,则抛出KeyError
。
my_set = {1, 2, 3}
removed = my_set.pop()
print(removed) # 可能是 1, 2, 或 3
print(my_set) # 剩余的两个元素
clear()
: 清空集合,使其变为空集合。
my_set = {1, 2, 3}
my_set.clear()
print(my_set) # set()
成员检查
使用 in
和 not in
操作符。这是集合非常高效的操作,时间复杂度接近 O(1)。
my_set = {1, 2, 3, "hello"}
print(2 in my_set) # True
print("world" not in my_set) # True
获取集合大小
my_set = {1, 2, 3}
print(len(my_set)) # 3
集合运算
集合支持丰富的数学集合运算,这些运算可以使用方法或操作符。
并集(Union):包含两个集合中所有不重复的元素。
set_a = {1, 2, 3}
set_b = {3, 4, 5}
union_set = set_a | set_b # 或 set_a.union(set_b)
print(union_set) # {1,2,3,4,5}
交集(Intersection):包含同时存在于两个集合中的元素。
set_a = {1, 2, 3}
set_b = {3, 4, 5}
inter_set = set_a & set_b # 或 set_a.intersection(set_b)
print(inter_set) # {3}
差集(Difference):包含在第一个集合中但不在第二个集合中的元素。
set_a = {1, 2, 3}
set_b = {3, 4, 5}
diff_set = set_a - set_b # 或 set_a.difference(set_b)
print(diff_set) # {3}
对称差集(Symmetric Difference):包含在两个集合中但不同时存在于两者中的元素。
set_a = {1, 2, 3}
set_b = {3, 4, 5}
sym_diff = set_a ^ set_b # 或者 set_a.symmetric_difference(set_b)
print(sym_diff) # {1, 2, 4, 5}
子集与超集判断
set1.issubset(set2)
或set1 <= set2
: 判断set1
是否是set2
的子集。set1.issuperset(set2)
或set1 >= set2
: 判断set1
是否是set2
的超集。set1 < set2
: 判断set1
是否是set2
的真子集(子集且不相等)。set1 > set2
: 判断set1
是否是set2
的真超集(超集且不相等)。
set_a = {1, 2}
set_b = {1, 2, 3}
print(set_a.issubset(set_b)) # True
print(set_b.issuperset(set_a)) # True
print(set_a < set_b) # True
print(set_a <= set_b) # True
print(set_a <= set_a) # True (子集可以等于自身)
print(set_a < set_a) # False (真子集不能等于自身)
不相交判断:如果两个集合没有交集(交集为空),返回
True
。
set_a = {1, 2}
set_b = {3, 4}
print(set_a.isdisjoint(set_b)) # True
集合推导式
类似于列表推导式,用于简洁地创建集合。
# 创建 0 到 9 的平方的集合
squares_set = {x**2 for x in range(5)}
print(squares_set) # {0, 1, 4, 9, 16}
# 从字符串中提取唯一的元音字母
text = "hello world"
vowels = {char for char in text if char in 'aeiou'}
print(vowels) # {'o', 'e'}
不可变集合
frozenset
是set
的不可变版本。创建后,使其元素不能被修改(不能添加、删除元素)。
因为不可变,所以
frozenset
本身是可哈希的,这意味着它可以作为字典的键或另一个集合的元素,而普通set
不行。创建方式:
frozenset(iterable)
。支持除了修改操作(
add
,remove
等)之外的所有集合运算(union
,intersection
,in
等)
# 创建 frozenset
fz = frozenset([1, 2, 3])
# fz.add(4) # AttributeError! 不可变
# 作为字典的键
dict_with_frozen_key = {frozenset([1, 2]): "a group"}
print(dict_with_frozen_key) # {frozenset({1, 2}): 'a group'}
# 作为集合的元素
set_of_sets = {frozenset([1, 2]), frozenset([3, 4])}
print(set_of_sets) # {frozenset({1, 2}), frozenset({3, 4})}
# set_of_sets = {{1, 2}, {3, 4}} # TypeError! set is unhashable
最后更新于