Python集合(set)

目录

集合

集合是无序和无索引的集合。在 Python 中,集合用花括号编写。

创建集合

创建集合:

python 复制代码
thisset = {"a", "b", "c"}
print(thisset)

访问集合

您无法通过引用索引来访问 set 中的项目,因为 set 是无序的,项目没有索引。

但是您可以使用 for 循环遍历 set 项目,或者使用 in 关键字查询集合中是否存在指定值。

实例

遍历集合,并打印值:

python 复制代码
thisset = {"a", "b", "c"}

for x in thisset:
  print(x)

向集合中添加和删除元素

集合一旦创建,您就无法更改元素,但是您可以添加新元素。

添加元素

要将一个元素添加到集合,请使用 add() 方法。

要向集合中添加多个元素,请使用 update() 方法。

实例

使用 add() 方法向 set 添加元素:

python 复制代码
thisset = {"a", "b", "c"}

thisset.add("d")

print(thisset)

实例

使用 update() 方法将多个元素添加到集合中:

python 复制代码
thisset = {"apple", "banana", "cherry"}

thisset.update(["orange", "mango", "grapes"])

print(thisset)

删除元素

要删除集合中的项目,请使用 remove()discard() 方法。

实例

使用 remove() 方法来删除 "b":

python 复制代码
thisset = {"a", "b", "c"}

thisset.remove("b")

print(thisset)
#如果要删除的项目不存在,则 remove() 将引发错误。

使用 discard() 方法来删除 "b":

python 复制代码
thisset = {"a", "b", "c"}

thisset.discard("b")

print(thisset)
#如果要删除的项目不存在,则 discard() 不会引发错误

集合的 交集,并集,差集运算

交集

intersection() 方法返回包含两个或更多集合之间相似性的集合。

含义:返回的集合仅包含两个集合中都存在的项目,或者如果使用两个以上的集合进行比较,则在所有集合中都存在
语法

python 复制代码
set.intersection(set1, set2 ... etc)

实例

返回包含存在于集合 x 和集合 y 中的项目的集合:

python 复制代码
x = {"a", "b", "c"}
y = {"s", "m", "a"}

z = x.intersection(y) 

print(z)

并集

union() 方法返回一个集合,其中包含原始集合中的所有项目以及指定集合中的所有项目。

您可以指定任意数量的集合,以逗号分隔。

如果一项存在于多个集合中,则该项在结果中仅出现一次。
语法

python 复制代码
set.union(set1, set2 ...)

实例

python 复制代码
x = {"a", "b", "c"}
y = {"f", "d", "a"}
z = {"c", "d", "e"}

result = x.union(y, z) 

print(result)

差集

symmetric_difference() 方法返回一个集合,其中包含两个集合中的所有项目,但不包含两个集合中都存在的项目。

含义:返回的集合包含两个集合中都不存在的项的混合体。
语法

python 复制代码
set.symmetric_difference(set)

实例

返回一个集合,其中包含两个集合中的所有项目,但两个集合中都存在的项目除外:

python 复制代码
x = {"a", "b", "c"}
y = {"s", "m", "a"}

z = x.symmetric_difference(y) 

print(z)

集合方法

相关推荐
TF男孩15 小时前
ARQ:一款低成本的消息队列,实现每秒万级吞吐
后端·python·消息队列
该用户已不存在20 小时前
Mojo vs Python vs Rust: 2025年搞AI,该学哪个?
后端·python·rust
站大爷IP1 天前
Java调用Python的5种实用方案:从简单到进阶的全场景解析
python
用户8356290780511 天前
从手动编辑到代码生成:Python 助你高效创建 Word 文档
后端·python
侃侃_天下1 天前
最终的信号类
开发语言·c++·算法
c8i1 天前
python中类的基本结构、特殊属性于MRO理解
python
echoarts1 天前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
liwulin05061 天前
【ESP32-CAM】HELLO WORLD
python
Aomnitrix1 天前
知识管理新范式——cpolar+Wiki.js打造企业级分布式知识库
开发语言·javascript·分布式
Doris_20231 天前
Python条件判断语句 if、elif 、else
前端·后端·python