彻底掌握Python集合:无序性、去重神器与高效集合运算指南

简介: 彻底掌握Python集合:无序性、去重神器与高效集合运算指南

Python 中的集合(set)是一种无序、可变且不重复的元素集合。集合常用于去重、数学集合运算(如并集、交集、差集等)以及其他需要唯一元素的场景。本文将详细介绍 Python 集合的基本语法、常用方法、示例代码、应用场景、注意事项及总结。

基本语法

创建集合

集合可以通过两种方式创建:使用花括号 {}set() 函数。

# 使用花括号创建集合
set1 = {1, 2, 3, 4}
print(set1)  # 输出: {1, 2, 3, 4}
# 使用 set() 函数创建集合
set2 = set([1, 2, 3, 4])
print(set2)  # 输出: {1, 2, 3, 4}
# 创建空集合只能用 set() 函数
empty_set = set()
print(empty_set)  # 输出: set()

常用方法

添加和删除元素
# 添加元素
set1.add(5)
print(set1)  # 输出: {1, 2, 3, 4, 5}
# 删除元素,如果元素不存在会引发 KeyError
set1.remove(3)
print(set1)  # 输出: {1, 2, 4, 5}
# 删除元素,如果元素不存在不会引发错误
set1.discard(3)
print(set1)  # 输出: {1, 2, 4, 5}
# 随机删除一个元素并返回
element = set1.pop()
print(element)  # 输出: 1 (结果可能不同)
print(set1)  # 输出: {2, 4, 5} (结果可能不同)
# 清空集合
set1.clear()
print(set1)  # 输出: set()
集合运算
set1 = {1, 2, 3}
set2 = {3, 4, 5}
# 并集
union_set = set1 | set2
print(union_set)  # 输出: {1, 2, 3, 4, 5}
# 交集
intersection_set = set1 & set2
print(intersection_set)  # 输出: {3}
# 差集
difference_set = set1 - set2
print(difference_set)  # 输出: {1, 2}
# 对称差集
symmetric_difference_set = set1 ^ set2
print(symmetric_difference_set)  # 输出: {1, 2, 4, 5}
其他方法
set1 = {1, 2, 3}
set2 = {2, 3}
# 判断子集
print(set2.issubset(set1))  # 输出: True
# 判断超集
print(set1.issuperset(set2))  # 输出: True
# 判断是否有交集
print(set1.isdisjoint(set({4, 5})))  # 输出: True
# 复制集合
set3 = set1.copy()
print(set3)  # 输出: {1, 2, 3}

示例

去除列表中的重复元素
my_list = [1, 2, 2, 3, 4, 4, 5]
my_set = set(my_list)
unique_list = list(my_set)
print(unique_list)  # 输出: [1, 2, 3, 4, 5]
集合运算示例
students_A = {"Tom", "Jerry", "Mike"}
students_B = {"Tom", "Mike", "Sara"}
# 两个班级的学生总数
all_students = students_A | students_B
print(all_students)  # 输出: {'Tom', 'Jerry', 'Mike', 'Sara'}
# 两个班级的共同学生
common_students = students_A & students_B
print(common_students)  # 输出: {'Tom', 'Mike'}
# 仅在 A 班级的学生
only_A_students = students_A - students_B
print(only_A_students)  # 输出: {'Jerry'}
# 不在共同的学生
unique_students = students_A ^ students_B
print(unique_students)  # 输出: {'Jerry', 'Sara'}

Python 集合的应用场景详解及示例

Python 集合是一种功能强大且高效的数据结构,适用于多个实际应用场景。下面详细介绍集合的四大主要应用场景,并附上示例代码。

1. 去重

集合的一个重要特性是它只能包含唯一的元素。这使得它成为从列表或其他可迭代对象中去除重复元素的理想工具。

示例代码:

# 原始列表包含重复元素
my_list = [1, 2, 2, 3, 4, 4, 5]
print("原始列表:", my_list)
# 使用集合去除重复元素
unique_set = set(my_list)
print("去重后的集合:", unique_set)
# 将集合转换回列表
unique_list = list(unique_set)
print("去重后的列表:", unique_list)

输出:

原始列表: [1, 2, 2, 3, 4, 4, 5]
去重后的集合: {1, 2, 3, 4, 5}
去重后的列表: [1, 2, 3, 4, 5]
2. 数学集合运算

集合支持多种数学集合运算,如并集、交集、差集和对称差集。这些运算非常适用于需要处理集合关系的场景。

示例代码:

set1 = {1, 2, 3}
set2 = {3, 4, 5}
# 并集
union_set = set1 | set2
print("并集:", union_set)  # 输出: {1, 2, 3, 4, 5}
# 交集
intersection_set = set1 & set2
print("交集:", intersection_set)  # 输出: {3}
# 差集
difference_set = set1 - set2
print("差集:", difference_set)  # 输出: {1, 2}
# 对称差集
symmetric_difference_set = set1 ^ set2
print("对称差集:", symmetric_difference_set)  # 输出: {1, 2, 4, 5}

输出:

并集: {1, 2, 3, 4, 5}
交集: {3}
差集: {1, 2}
对称差集: {1, 2, 4, 5}
3. 元素查找

集合的查找操作时间复杂度为 O(1),这使得集合非常适用于需要快速查找元素的场景。

示例代码:

# 创建一个集合
my_set = {1, 2, 3, 4, 5}
# 查找元素是否在集合中
print(3 in my_set)  # 输出: True
print(6 in my_set)  # 输出: False

输出:

True
False
4. 集合关系判断

集合提供了丰富的方法来判断集合之间的关系,如子集、超集和是否有交集等。这在需要判断集合关系的场景中非常有用。

示例代码:

set1 = {1, 2, 3}
set2 = {2, 3}
# 判断子集
is_subset = set2.issubset(set1)
print("set2 是 set1 的子集:", is_subset)  # 输出: True
# 判断超集
is_superset = set1.issuperset(set2)
print("set1 是 set2 的超集:", is_superset)  # 输出: True
# 判断是否有交集
has_intersection = set1.isdisjoint({4, 5})
print("set1 与 {4, 5} 没有交集:", has_intersection)  # 输出: True

输出:

set2 是 set1 的子集: True
set1 是 set2 的超集: True
set1 与 {4, 5} 没有交集: True

Python 集合详解:不可变元素、无序性、性能考虑及使用可变集合的注意事项

Python 集合是一种强大的数据结构,具备高效的查找、插入和删除操作。为了充分利用集合的优势,并避免常见的陷阱和问题,需要了解以下几个关键点:集合元素的不可变性、集合的无序性、性能考虑及使用可变集合的注意事项。

1. 集合元素必须是不可变的

集合中的元素必须是可哈希的,即元素必须是不可变类型。常见的不可变类型包括整数、字符串和元组等。

示例代码:

# 可以作为集合元素的类型
immutable_set = {1, "hello", (2, 3)}
print("集合:", immutable_set)
# 尝试使用列表作为集合元素(会报错)
try:
    invalid_set = {1, [2, 3]}
except TypeError as e:
    print("错误:", e)

输出:

集合: {1, (2, 3), 'hello'}
错误: unhashable type: 'list'
2. 集合是无序的

集合不保证元素的顺序,因此不能依赖集合的顺序。如果需要有序集合,可以使用 collections.OrderedDict 来实现。

示例代码:

from collections import OrderedDict
# 集合是无序的
unordered_set = {3, 1, 2}
print("无序集合:", unordered_set)
# 使用 OrderedDict 实现有序集合
ordered_dict = OrderedDict.fromkeys([3, 1, 2])
ordered_set = set(ordered_dict.keys())
print("有序集合:", ordered_set)

输出:

无序集合: {1, 2, 3}
有序集合: {3, 1, 2}
3. 性能考虑

集合的查找、添加、删除操作的时间复杂度为 O(1),但在处理大量数据时,仍需注意内存消耗问题。

示例代码:

# 创建一个包含大量数据的集合
large_set = set(range(1000000))
# 查找操作
print("查找 999999:", 999999 in large_set)
# 添加操作
large_set.add(1000001)
print("添加元素后集合大小:", len(large_set))
# 删除操作
large_set.remove(500000)
print("删除元素后集合大小:", len(large_set))

输出:

查找 999999: True
添加元素后集合大小: 1000001
删除元素后集合大小: 1000000
4. 小心使用可变集合

普通集合是不可哈希的,不能作为其他集合的元素。如果需要在集合中包含集合,可以使用 frozenset,因为 frozenset 是不可变的,可以作为集合的元素。

示例代码:

# 尝试将普通集合作为元素(会报错)
try:
    invalid_nested_set = {frozenset({1, 2}), {3, 4}}
except TypeError as e:
    print("错误:", e)
# 使用 frozenset 作为元素
valid_nested_set = {frozenset({1, 2}), frozenset({3, 4})}
print("包含 frozenset 的集合:", valid_nested_set)

输出:

错误: unhashable type: 'set'
包含 frozenset 的集合: {frozenset({3, 4}), frozenset({1, 2})}

总结

Python 集合是一种非常有用的数据结构,具有无序、可变、去重的特点,适用于需要集合运算和唯一性判断的场景。通过理解和掌握集合的基本语法和常用方法,可以有效地进行数据处理和性能优化。在实际应用中,需要注意集合的不可变性和性能问题,合理使用集合的特性来解决实际问题。

相关文章
|
30天前
|
数据采集 关系型数据库 MySQL
2024年最全python进阶系列- 04 集合,2024年最新哈希表 面试
2024年最全python进阶系列- 04 集合,2024年最新哈希表 面试
|
30天前
|
开发工具 Python 容器
2024年最全python进阶系列- 04 集合(1),面试高频问题回答
2024年最全python进阶系列- 04 集合(1),面试高频问题回答
2024年最全python进阶系列- 04 集合(1),面试高频问题回答
|
5天前
|
存储 索引 Python
【Python列表解锁】:掌握序列精髓,驾驭动态数据集合
【Python列表解锁】:掌握序列精髓,驾驭动态数据集合
|
5天前
|
存储 Python 容器
Python零基础入门-5 数据结构(集合和字典)
Python零基础入门-5 数据结构(集合和字典)
|
8天前
|
机器学习/深度学习 算法 Serverless
利用无穷级数逼近计算幂运算与开根号——Python实现
使用泰勒级数逼近法,本文介绍了如何用Python计算特殊幂运算,包括分数次幂和开根号。通过定义辅助函数,如`exp`、`getN_minus_n`、`multi`和`getnum`,实现了计算任意实数次幂的功能。实验结果显示,算法能有效计算不同情况下的幂运算,例如`0.09^2`、`1^2`、`0.25^2`、`0.09^(0.5)`、`1^(0.5)`和`0.25^(0.5)`。虽然精度可能有限,但可通过调整迭代次数平衡精度与计算速度。
|
12天前
|
存储 数据处理 Python
Python3 运算符大解密:掌握运算法宝,事半功倍!
Python3 运算符大解密:掌握运算法宝,事半功倍!
|
14天前
|
Python
【Python 训练营】N_15 列表元素去重
【Python 训练营】N_15 列表元素去重
14 1
|
15天前
|
运维 索引 Python
9.Python【非序列】- 集合
9.Python【非序列】- 集合
21 2
|
16天前
|
Python
|
19天前
|
索引 Python
Python集合的定义与操作详解
Python集合的定义与操作详解
6 1