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)

集合方法

相关推荐
宿州派大星2 小时前
Python实战:PyQt5 + OpenCV + Dlib 打造AI桌面应用
人工智能·python·qt
承渊政道3 小时前
【从零开始大模型开发与微调:基于PyTorch与ChatGLM】(开源大模型ChatGLM高级定制化应用实战)
人工智能·pytorch·python·llm·模型微调·glm
Joy T5 小时前
Agent 确定性上下文设计:从 Prompt 参数注入到能力分层
java·开发语言·微服务·架构·prompt·agent context
专注仿真8 小时前
引擎扩展性与集成设计深度剖析:从 14 个扩展点到 DIS→HLA 演进之路
开发语言·算法·仿真引擎·推演引擎
Best-Wishes9 小时前
科来网络分析系统(技术交流版)使用说明书
开发语言·junit·php
代码不停9 小时前
自动化测试(java)
java·开发语言·selenium·自动化
Smoothcloud润云10 小时前
PyTorch大模型权重加载与启动耗时优化实战:定位磁盘、内存与显存瓶颈
人工智能·pytorch·python·深度学习·gpu算力
databook10 小时前
从循环到向量化:NumPy提速的7个关键思维
python·数据分析·numpy
棉猴10 小时前
玩游戏学Python1-Python和pgzero库的安装
python·pygame·玩游戏·pgzero·pgzrun
诺伦11 小时前
GEO优化数据实证:78%引用流向官网的机制拆解与小品牌三步管线实战教程 | RiseClaw玄策
python·seo·geo·内容营销·ai搜索