Python集合函数详解及应用258


Python的集合(set)是一种无序、不可重复元素的集合。它提供了一系列内置函数,方便我们进行集合操作,例如添加元素、删除元素、集合运算(并集、交集、差集、对称差集)等等。熟练掌握这些函数,能够有效地提高代码效率和可读性。本文将详细介绍Python集合的常用函数,并结合示例进行讲解。

1. 创建集合

创建集合可以使用花括号`{}`或`set()`函数。需要注意的是,使用花括号创建空集合时,必须使用`set()`,因为`{}`表示的是空字典。
# 使用花括号创建集合
my_set = {1, 2, 3, 4}
print(my_set) # Output: {1, 2, 3, 4}
# 使用set()函数创建集合
my_set = set([1, 2, 3, 4]) # 从列表创建
print(my_set) # Output: {1, 2, 3, 4}
my_set = set("hello") # 从字符串创建,元素为字符
print(my_set) # Output: {'h', 'e', 'l', 'o'}
empty_set = set() # 创建空集合
print(empty_set) # Output: set()


2. 添加元素

可以使用`add()`方法添加单个元素,使用`update()`方法添加多个元素(可以是迭代器,如列表、元组等)。
my_set = {1, 2, 3}
(4)
print(my_set) # Output: {1, 2, 3, 4}
([5, 6, 7])
print(my_set) # Output: {1, 2, 3, 4, 5, 6, 7}
({8,9}, (10,)) # 可以同时添加多个不同类型的可迭代对象
print(my_set) # Output: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

3. 删除元素

Python提供了多种删除元素的方法:`remove()`、`discard()`和`pop()`。 `remove()`方法如果元素不存在则会引发`KeyError`异常,而`discard()`方法则不会。`pop()`方法会随机删除并返回一个元素,如果集合为空则引发`KeyError`。
my_set = {1, 2, 3, 4}
(3)
print(my_set) # Output: {1, 2, 4}
(5) # 5 不存在,不会报错
print(my_set) # Output: {1, 2, 4}
removed_element = ()
print(removed_element) # Output: (随机一个元素,例如1)
print(my_set) # Output: {2,4} (剩余元素)


4. 集合运算

Python集合支持常见的集合运算:并集(union)、交集(intersection)、差集(difference)、对称差集(symmetric_difference)。这些运算可以使用`|`、`&`、`-`、`^`符号或对应的函数`union()`、`intersection()`、`difference()`、`symmetric_difference()`来实现。
set1 = {1, 2, 3}
set2 = {3, 4, 5}
# 并集
union_set = set1 | set2
print(union_set) # Output: {1, 2, 3, 4, 5}
print((set2)) # Output: {1, 2, 3, 4, 5}
# 交集
intersection_set = set1 & set2
print(intersection_set) # Output: {3}
print((set2)) # Output: {3}
# 差集
difference_set = set1 - set2
print(difference_set) # Output: {1, 2}
print((set2)) # Output: {1, 2}
# 对称差集
symmetric_difference_set = set1 ^ set2
print(symmetric_difference_set) # Output: {1, 2, 4, 5}
print(set1.symmetric_difference(set2)) # Output: {1, 2, 4, 5}

5. 其他常用函数

除了以上介绍的函数外,Python集合还有一些其他的常用函数:
len(set): 返回集合中元素的个数。
in 和 not in: 判断元素是否在集合中。
issubset(other_set): 判断当前集合是否是另一个集合的子集。
issuperset(other_set): 判断当前集合是否是另一个集合的超集。
isdisjoint(other_set): 判断两个集合是否不相交。
copy(): 创建集合的浅拷贝。
clear(): 清空集合。



set1 = {1, 2, 3}
set2 = {1, 2, 3, 4, 5}
print(len(set1)) # Output: 3
print(2 in set1) # Output: True
print((set2)) # Output: True
print((set1)) # Output: True
print(({4,5,6})) # Output: True
set3 = ()
print(set3) # Output: {1, 2, 3}
()
print(set1) # Output: set()

总结

Python集合及其内置函数提供了强大的集合操作功能,在数据处理、算法设计等方面具有广泛的应用。熟练掌握这些函数,可以编写出更高效、更简洁的代码。 希望本文能够帮助你更好地理解和运用Python集合。

2025-06-27


上一篇:Python实现高效的数据关联算法:从基础到进阶

下一篇:Python 数据持久化:选择合适的方案