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)

集合方法

相关推荐
hboot11 小时前
AI工程师第二课 - 数据处理
人工智能·python·数据分析
用户83562907805115 小时前
使用 Python 自动化 PowerPoint 形状布局与格式设置
后端·python
用户83562907805117 小时前
用 Python 自动化 PowerPoint 演讲者备注添加
后端·python
黄忠1 天前
01-系统架构设计-LangGraph状态机与多源异构RAG
python
zzzzzz3101 天前
假如我是掘金管理员,我先给评论区装个'代码审查'系统
python·程序员·机器人
砍材农夫1 天前
python环境|conda安装和使用(2)
后端·python
程序员龙叔2 天前
编写高质量 Skill 系列 -- 如何设计需求分析与用例生成的 SKILL
自动化测试·软件测试·python·软件测试工程师·接口测试·性能测试·skill·ai测试
用户8356290780512 天前
使用 Python 操作 Word 内容控件
后端·python
LDR0062 天前
Type-C 快充全面升级!LDR6601 赋能个人护理便携电机,重塑剃须刀 / 理发器新体验
c语言·开发语言
雪碧聊技术2 天前
Tree.js是什么?一文讲透
开发语言·javascript·ecmascript