python之Set操作(上)

本文介绍了Python中Set的创建,包括普通Set、不可变Set和空Set的创建方式;Set的复制,涉及浅拷贝和深拷贝的实现;基础操作如获取Set长度;以及如何向Set中添加元素,包括单个元素、多个元素和Set集合的添加。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

python之Set操作(上)

Set是一个无序不重复元素的集:

  1. 具有无序性,所以本章节的举例运行结果可能不尽相同,但set所包含的元素是相同的(随即删除元素除外);
  2. 具有互异性,即set中的元素不可以重复出现,对于某些需要去重的场景,这是一个很好的实践;
  3. 元素必须是不可变对象,比如数字、字符串或元组(纯元组,没有嵌套可变对象)

1. Set创建

1) 创建Set

创建Set实例,对于不可变Set场景,参见“创建不可变Set”,对于空Set场景,参见“创建Empty Set”
推荐写法: 使用Python3的标准库,set类内置函数:set([iterable]),iterable是可选参数,指代一个可迭代对象(如字符串、列表、元组和字典等)

  • 先初始化,再赋值
  • 不可以传递数字参数
  • 元素必须是不可变对象,比如数字、字符串或元组(纯元组,没有嵌套可变对象),否则抛出TypeError
set1 = set()
set1 = {1, 2, 3, 4, 5}
print(set1)  # {1, 2, 3, 4, 5}

wrong_set1 = set(1)  # 抛出TypeError: 'int' object is not iterable
tuple1 = ("python", "java", [1, 2, 3])
wrong_set2 = {"hello", tuple1}  # 抛出TypeError: unhashable type: 'list'

一般写法: 使用{}直接初始化

  • 缺点:不可以用于创建空集合,因为{}创建的是空字典
  • 元素必须是不可变对象,比如数字、字符串或元组(纯元组,没有嵌套可变对象),否则抛出TypeError
set2 = {1, 2, 3, 4, 5}
print(set2) # {1, 2, 3, 4, 5}

wrong_set1 = {}
print(isinstance(wrong_set1, set))  # False
print(isinstance(wrong_set1, dict))  # {}是字典类型 True

list1 = [1, 2, 3]
wrong_set2 = {"hello", list1}  # 抛出TypeError: unhashable type: 'list'
2) 创建不可变Set

创建不可变Set,不可变集合没有add、remove、update等方法,不允许修改集合元素
推荐写法: 使用Python3的标准库,frozenset类内置函数:frozenset([iterable]),iterable是可选参数,指代一个可迭代对象(如字符串、列表、元组和字典等)

  • 用法说明同函数set([iterable])
  • 若不传递参数,则创建一个空的不可变Set
frozen_set = frozenset("hello")
print(frozen_set)  # frozenset({'h', 'l', 'o', 'e'})

empty_frozenset = frozenset()
print(empty_frozenset)  # frozenset()
3) 创建Empty Set

创建空集合
推荐写法: 使用Python3的标准库,set类内置函数:set()

  • 想要创建空集合,必须使用set()而不是{},后者用于创建空字典
empty_set = set()
print(isinstance(empty_set, set))  # True
print(empty_set)  # set()

wrong_set = {}
print(isinstance(wrong_set, set))  # False
print(isinstance(wrong_set, dict))  # {}是字典类型 True

2. Set复制

1) Set浅拷贝

Set浅拷贝只会拷贝当前Set的顶层元素,不会拷贝嵌套的子对象,即原Set和拷贝Set指向同一子对象
一般写法: 使用Python3的标准库,set类内置函数:copy(other),other指代另一个Set

  • 返回一个新Set,与原Set地址空间不同
  • 若当前Set包含子对象,则不会拷贝子对象,原Set和拷贝Set指向同一子对象
  • 更新子对象会同时影响原Set和拷贝Set(因为Set的元素是不可变对象,所以这里无法通过修改子对象元素 来验证这一特性)
set1 = {"hello", "world", ("python", "java")}
copy1 = set1.copy()

print(set1 == copy1)  # True
print(id(set1) == id(copy1))  # False

copy1.clear()
print(set1)  # {'hello', 'world', ('python', 'java')}

一般写法: 使用Python3的标准库,copy模块的函数:copy(other),other指代另一个Set

  • 需要导入copy模块
  • 说明同上
import copy

set1 = {"hello", "world", ("python", "java")}

copy1 = copy.copy(set1)
print(set1 == copy1)  # True
print(id(set1) == id(copy1))  # False

copy1.clear()
print(set1)  # {'hello', 'world', ('python', 'java')}

一般写法: 使用Python3的标准库,set类内置函数:set(other),other指代另一个Set

  • 说明同上
set1 = {"hello", "world", ("python", "java")}

copy1 = set(set1)
print(set1 == copy1)  # True
print(id(set1) == id(copy1))  # False

copy1.clear()
print(set1)  # {'hello', 'world', ('python', 'java')}

一般写法: 使用运算符”=“

  • 本质是对象的引用
  • 返回一个新Set,与原Set指向同一个地址空间,相互影响
set1 = {"hello", "world", ("python", "java")}

copy1 = set1
print(set1 == copy1)  # True
print(id(set1) == id(copy1))  # True

copy1.clear()
print(set1)  # set()
2) Set深拷贝

Set深拷贝不仅会拷贝当前Set的顶层元素,也会拷贝嵌套的子对象,本质上是执行递归浅拷贝,原Set和拷贝Set完全独立,相互不影响
推荐写法: 使用Python3的标准库,copy模块的函数:deepcopy(other),other指代另一个Set

  • 需要导入copy模块
  • 返回一个新Set,与原Set是独立的对象,地址空间不同 若当前Set包含子对象,也会拷贝子对象
  • 原Set和拷贝Set所有元素地址都是独立的,更新元素相互不影响
import copy

set1 = {"hello", "world", ("python", "java")}

copy1 = copy.deepcopy(set1)
print(set1 == copy1)  # True
print(id(set1) == id(copy1))  # False

copy1.clear()
print(set1)  # {'hello', 'world', ('python', 'java')}

3. Set基础操作

1) 获取Set长度

获取Set长度
推荐写法: 使用Python3的标准库,内置函数:len(s),参数可以是序列(如字符串、字节、元组、列表或范围等)或集合(如字典和集合),这里是Set实例

  • 返回对象的长度
set1 = {"hello", "world"}
length = len(set1)
print(length)  # 2

empty_set = set()
empty_length = len(empty_set)
print(empty_length)  # 0

frozen_set = frozenset("hello")
frozenset_length = len(frozen_set)
print(frozenset_length)  # 4

4. Set添加

Set添加元素,以下操作对象是可变集合

1) 添加单个元素

Set添加单个元素
推荐写法: 使用Python3的标准库,set类内置函数:add(elem),elem指定要添加的元素

  • 修改当前集合,添加一个指定元素
  • 若要添加的元素在Set中已存在,则不执行任何操作
set1 = {"hello", "world"}
set1.add(2)
print(set1)  # {'hello', 2, 'world'}

set1.add("hello")
print(set1)  # {'hello', 2, 'world'}
2) 添加多个元素

Set添加多个元素
*推荐写法: 使用Python3的标准库,set类内置函数:update(iterables),iterables指代可迭代对象

  • 修改当前集合,添加一个或多个元素
  • 若要添加的元素在集合中已存在,则该元素只会出现一次,重复的会被忽略
  • 接受多个可迭代对象参数,多个参数使用逗号”,“隔开
set1 = {"hello", "world"}
set1.update(["hello", "python"], "abc", (1, 2, 3), {11.11})
print(set1)  # {1, 2, 3, 'a', 'world', 'c', 11.11, 'b', 'python', 'hello'}

set1.update(123)  # 抛出TypeError: 'int' object is not iterable
3) 添加Set集合

Set添加Set集合
*推荐写法: 使用Python3的标准库,set类内置函数:update(others),others指代其它Set实例

  • 修改当前集合,添加Set集合
  • 若添加的元素在集合中已存在,则该元素只会出现一次,重复的会被忽略
  • 接受多个Set对象参数,多个参数使用逗号”,“隔开
set1 = {"hello", "world"}
set1.update({"hello", "world", "python", 2})
print(set1)  # {'python', 2, 'hello', 'world'}

set1.update({1, 2, 3}, {"huawei", "com"}, {"update", "set"})
print(set1)  # {'set', 1, 2, 3, 'huawei', 'com', 'python', 'world', 'update', 'hello'}
### Python Set Operations Examples and Explanation Sets in Python are collections of unique elements with no repeated values. Sets support mathematical operations like union, intersection, difference, and symmetric difference. #### Creating a Set To create a set, one can use curly braces `{}` or the `set()` function. ```python example_set = {1, 2, 3} another_set = set([4, 5, 6]) ``` #### Adding Elements to a Set Elements can be added using the `.add()` method[^1]. ```python example_set.add(4) print(example_set) # Output will include 4 as well ``` #### Removing Elements from a Set The removal of an element can occur through methods such as `.remove()`, which raises an error if the item does not exist; alternatively, `.discard()` may be used without raising errors when attempting to remove non-existent items. #### Union Operation Union combines two sets into one containing all distinct members found within either original collection. ```python combined_set = example_set.union(another_set) # Alternatively, combined_set = example_set | another_set ``` #### Intersection Operation Intersection creates a new set consisting only of those elements common between both initial sets. ```python common_elements = example_set.intersection(another_set) # Or equivalently, common_elements = example_set & another_set ``` #### Difference Operation Difference results in a set that contains just the elements present in the first but absent from the second specified set. ```python unique_to_example = example_set.difference(another_set) # Also possible via operator, unique_to_example = example_set - another_set ``` #### Symmetric Difference Operation Symmetric difference yields a set made up exclusively of elements appearing exactly once across the pair of inputted sets – meaning they appear in precisely one out of these two inputs rather than being shared by them equally. ```python exclusive_members = example_set.symmetric_difference(another_set) # Can also write it this way, exclusive_members = example_set ^ another_set ``` --related questions-- 1. How do you check whether there exists any overlap at all between multiple given sets? 2. In what ways could understanding how sets work improve performance optimization efforts during coding tasks involving large datasets? 3. Are there specific scenarios where utilizing frozen sets instead of regular mutable ones would prove beneficial over others? 4. What advantages might come from employing set comprehensions compared against traditional loop constructs while manipulating data structures similar to lists or dictionaries? 5. Could someone provide real-world applications demonstrating effective usage patterns around membership testing inside conditional statements alongside iteration protocols provided inherently by pythonic style guides?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值