在 Python 中,set()函数的作用是创建一个无序、不重复元素的可变集合。

函数语法

set([iterable])

参数:

  • iterable:任何可迭代对象;缺省时创建一个空集合;

返回一个set对象;

集合(Set)

集合是 Python 中的一种无序、不重复的数据结构,基于哈希表实现。

创建集合

使用set()函数创建集合:

# 从列表创建
lst = set(["a", "b", "c"])
print(lst)  # {'a', 'b', 'c'}

# 从元组创建
numbers = set((1, 2, 3, 2, 1))
print(numbers)  # {1, 2, 3}

# 从字符串创建
chars = set("hello")
print(chars)  # {'e', 'h', 'l', 'o'}

# 从范围创建
range_set = set(range(5))
print(range_set)  # {0, 1, 2, 3, 4}

# 从字典创建,只获取键
dict_set = set({"a": 1, "b": 2})
print(dict_set)  # {'a', 'b'}

也可使用花括号{}来创建非空集合:

# 创建有元素的集合
set1 = {"a", "b", "c"}
print(set1)  # {'a', 'b', 'c'}
# 使用推导式
set2 = {x for x in range(5)}
print(set2)  # {0, 1, 2, 3, 4}

# 不能用{}创建空集合
empty_set = {}  # 这是字典,不是集合
print(type(empty_set))  # <class 'dict'>

# 正确创建空集合
empty_set = set()
print(type(empty_set))  # <class 'set'>

集合的特性

集合的元素是无序的、唯一的、可哈希的;

# 无序的,每次运行都不同
print(set('hello')) # {'e', 'l', 'h', 'o'}
# 唯一的,会自动去重
print(set([1,1,1])) # {1}
# 可哈希的,即元素必须不可变
s = {123,"hello",(1,2,3)} # {123, 'hello', (1, 2, 3)}
print(s)
# s = {[]} # TypeError

集合的基本操作

s = {1, 2, 3}

# 添加元素
s.add(4)
s.add(2)
print(s)  # {1, 2, 3, 4}

# 删除元素
s.remove(3)
print(s)  # {1, 2, 4}

# 删除不存在的元素会报错
try:
    s.remove(5)
except KeyError as e:
    print(f"KeyError: {e}")

# 安全删除,不会报错
s.discard(5)
s.discard(2)
print(s)  # {1, 4}

# 弹出元素,随机的
popped = s.pop()

# 清空集合
s.clear()
print(s)  # set()

# 检查元素是否存在
s = {1, 2, 3}
print(2 in s)  # True
print(5 in s)  # False

集合的运算

A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}

# 并集
print(A | B) 
print(A.union(B))

# 交集
print(A & B)
print(A.intersection(B))

# 差集,A有B没有
print(A - B)
print(A.difference(B))

# 对称差集,不同时属于A和B的元素
print(A^B)
print(A.symmetric_difference(B))

集合关系判断

X = {1, 2, 3}
Y = {1, 2}
Z = {3, 4}

# 子集判断
print(f"Y ⊆ X? {Y.issubset(X)}")  # True
print(f"Y <= X? {Y <= X}")  # True

# 真子集判断
print(f"Y ⊂ X? {Y < X}")  # True (Y是X的真子集)

# 超集判断
print(f"X ⊇ Y? {X.issuperset(Y)}")  # True
print(f"X >= Y? {X >= Y}")  # True

# 真超集判断
print(f"X ⊃ Y? {X > Y}")  # True

# 是否不相交
print(f"X ∩ Z = ∅? {X.isdisjoint(Z)}")  # False (有交集3)
print(f"Y ∩ Z = ∅? {Y.isdisjoint(Z)}")  # True (无交集)

集合的修改操作

A = {1, 2, 3}
B = {3, 4, 5}

# 添加多个元素
A.update([4, 5, 6])

# 交集更新,保留共有的)
A = {1, 2, 3}
A.intersection_update(B)

# 差集更新,移除B中也有的元素
A = {1, 2, 3, 4}
A.difference_update(B)

# 对称差集更新
A = {1, 2, 3}
A.symmetric_difference_update(B)

集合的实用方法

s = {1, 2, 3}
# 复制集合
shallow_copy = s.copy()
# 集合的长度
length = len(s)
# 遍历集合
for item in s:
    print(item)