Python 第五节 Set()集合使用详解及注意事项
·
1、Set 简介
Set 是 Python 中的一种无序、不重复元素集,基本功能包括关系测试和消除重复元素。Set 对象支持数学运算如并集、交集、差集和对称差集。
2、Set 基本操作
2.1、创建 Set
# 使用花括号创建
fruits = {'apple', 'orange', 'banana', 'apple'}
print(fruits) # 输出: {'banana', 'orange', 'apple'} (重复项被移除)
# 使用 set() 构造函数
numbers = set([1, 2, 3, 2, 1])
print(numbers) # 输出: {1, 2, 3}
# 空集合必须使用 set() 而不是 {}
empty_set = set()
print(type(empty_set)) # 输出: <class 'set'>
2.2、添加和删除元素
my_set = {1, 2, 3}
# 添加元素
my_set.add(4)
print(my_set) # 输出: {1, 2, 3, 4}
# 添加多个元素
my_set.update([5, 6, 7])
print(my_set) # 输出: {1, 2, 3, 4, 5, 6, 7}
# 删除元素 (如果元素不存在会引发 KeyError)
my_set.remove(3)
print(my_set) # 输出: {1, 2, 4, 5, 6, 7}
# 安全删除元素 (如果元素不存在不会报错)
my_set.discard(10)
print(my_set) # 输出不变
# 随机删除并返回一个元素
popped = my_set.pop()
print(f"删除了: {popped}, 剩余: {my_set}")
# 清空集合
my_set.clear()
print(my_set) # 输出: set()
2.3、集合运算
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# 并集
print(A | B) # 输出: {1, 2, 3, 4, 5, 6, 7, 8}
print(A.union(B)) # 同上
# 交集
print(A & B) # 输出: {4, 5}
print(A.intersection(B)) # 同上
# 差集 (在A中但不在B中)
print(A - B) # 输出: {1, 2, 3}
print(A.difference(B)) # 同上
# 对称差集 (在A或B中,但不同时在两者中)
print(A ^ B) # 输出: {1, 2, 3, 6, 7, 8}
print(A.symmetric_difference(B)) # 同上
2.4、集合比较
C = {1, 2}
D = {1, 2, 3}
# 子集检查
print(C.issubset(D)) # 输出: True
print(C <= D) # 同上
# 真子集检查
print(C < D) # 输出: True
# 超集检查
print(D.issuperset(C)) # 输出: True
print(D >= C) # 同上
# 真超集检查
print(D > C) # 输出: True
# 不相交检查
E = {4, 5}
print(C.isdisjoint(E)) # 输出: True
3、Set注意事项
Set 中的元素必须是不可变的(数字、字符串、元组等),不能包含列表、字典或其他可变类型
# 这会报错
# invalid_set = {[1, 2], [3, 4]}
# 但可以包含元组
valid_set = {(1, 2), (3, 4)}
# Set 是无序的,不能通过索引访问元素
my_set = {'a', 'b', 'c'}
# print(my_set[0]) # 这会报错
# 使用 set() 而不是 {} 创建空集合;{}创建的事 字典项
empty_dict = {} # 这是一个空字典
empty_set = set() # 这是一个空集合
# Set 对于成员检测非常高效(O(1)时间复杂度),比列表快得多
# 对于大型数据集,使用集合进行成员检测更高效
large_list = list(range(1000000))
large_set = set(large_list)
# 测试列表成员检测 (较慢)
# 999999 in large_list
# 测试集合成员检测 (很快)
# 999999 in large_set
4、Set使用实际应用案例
4.1、数据去重
# 从列表中去除重复项
names = ['Alice', 'Bob', 'Alice', 'Charlie', 'Bob']
unique_names = list(set(names))
print(unique_names) # 输出: ['Charlie', 'Bob', 'Alice'] (顺序可能不同)
4.2、查找共同元素
# 找出两个列表中的共同朋友
my_friends = {'Alice', 'Bob', 'Charlie', 'David'}
her_friends = {'Bob', 'David', 'Eve', 'Frank'}
common_friends = my_friends & her_friends
print(common_friends) # 输出: {'Bob', 'David'}
4.3、词频统计辅助
# 使用集合快速检查是否已处理过某个词
text = "the quick brown fox jumps over the lazy dog"
words = text.split()
seen_words = set()
unique_words = []
for word in words:
if word not in seen_words:
unique_words.append(word)
seen_words.add(word)
print(unique_words) # 输出: ['the', 'quick', 'brown', 'fox', 'jumps', 'over', 'lazy', 'dog']
4.4、权限管理系统
# 使用集合管理用户权限
class User:
def __init__(self, name):
self.name = name
self.permissions = set()
def add_permission(self, permission):
self.permissions.add(permission)
def has_permission(self, permission):
return permission in self.permissions
def has_all_permissions(self, required_permissions):
return required_permissions.issubset(self.permissions)
def has_any_permission(self, required_permissions):
return not self.permissions.isdisjoint(required_permissions)
# 创建用户并分配权限
user = User("Alice")
user.add_permission("read")
user.add_permission("write")
# 检查权限
print(user.has_permission("read")) # 输出: True
print(user.has_permission("delete")) # 输出: False
required = {"read", "write"}
print(user.has_all_permissions(required)) # 输出: True
any_required = {"write", "delete"}
print(user.has_any_permission(any_required)) # 输出: True (因为有write权限)
更多推荐



所有评论(0)