本文目录导读:

在Python中,集合(set)新增数据主要有以下几种方法:
add() 方法 - 添加单个元素
# 创建一个空集合
my_set = set()
# 添加单个元素
my_set.add(1)
my_set.add(2)
my_set.add(3)
print(my_set) # 输出: {1, 2, 3}
# 添加重复元素不会生效
my_set.add(1)
print(my_set) # 输出: {1, 2, 3}
update() 方法 - 添加多个元素
# 添加列表中的元素
my_set = {1, 2}
my_set.update([3, 4, 5])
print(my_set) # 输出: {1, 2, 3, 4, 5}
# 添加另一个集合
another_set = {6, 7}
my_set.update(another_set)
print(my_set) # 输出: {1, 2, 3, 4, 5, 6, 7}
# 添加字符串
my_set.update("abc")
print(my_set) # 输出: {1, 2, 3, 4, 5, 6, 7, 'a', 'b', 'c'}
使用 | 运算符 - 合并两个集合
set1 = {1, 2, 3}
set2 = {3, 4, 5}
# 合并两个集合
result = set1 | set2
print(result) # 输出: {1, 2, 3, 4, 5}
# 也可以使用 union() 方法
result2 = set1.union(set2)
print(result2) # 输出: {1, 2, 3, 4, 5}
实际应用案例
案例1:去重并新增数据
# 场景:清除重复的邮箱地址并添加新邮箱
existing_emails = {"alice@example.com", "bob@example.com"}
new_emails = ["bob@example.com", "charlie@example.com", "david@example.com"]
# 使用 update 批量添加(自动去重)
existing_emails.update(new_emails)
print(existing_emails)
# 输出: {'alice@example.com', 'bob@example.com', 'charlie@example.com', 'david@example.com'}
案例2:用户权限管理
# 场景:动态为用户添加权限
user_permissions = set()
# 逐步添加权限
user_permissions.add("read")
user_permissions.add("write")
print(user_permissions) # 输出: {'read', 'write'}
# 批量添加更多权限
admin_permissions = ["delete", "execute", "manage"]
user_permissions.update(admin_permissions)
print(user_permissions)
# 输出: {'read', 'write', 'delete', 'execute', 'manage'}
案例3:合并两个数据源
# 场景:合并两个来源的商品ID列表
source1 = {101, 102, 103, 104}
source2 = {103, 104, 105, 106}
# 方法1:使用 update
combined1 = source1.copy() # 复制以避免修改原集合
combined1.update(source2)
print(combined1) # 输出: {101, 102, 103, 104, 105, 106}
# 方法2:使用 |
combined2 = source1 | source2
print(combined2) # 输出: {101, 102, 103, 104, 105, 106}
注意事项
- 集合是无序的,添加的元素位置不确定
- 集合中的元素必须是不可变类型(数字、字符串、元组等)
- 添加重复元素不会报错,但不会生效
- 使用
add()添加单个元素,update()添加可迭代对象中的多个元素
# 错误示例 - 不能添加可变类型
my_set = set()
# my_set.add([1, 2]) # TypeError: unhashable type: 'list'
# 正确做法 - 添加元组
my_set.add((1, 2))
print(my_set) # 输出: {(1, 2)}
这些方法可以根据实际需求灵活使用,实现高效的数据集合管理。