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)

集合方法

相关推荐
Rockbean13 分钟前
用40行代码搭建自己的无服务器OCR
服务器·python·deepseek
曲幽1 小时前
FastAPI + Ollama 实战:搭一个能查天气的AI助手
python·ai·lora·torch·fastapi·web·model·ollama·weatherapi
用户60648767188962 小时前
国内开发者如何接入 Claude API?中转站方案实战指南(Python/Node.js 完整示例)
人工智能·python·api
只与明月听2 小时前
RAG深入学习之Chunk
前端·人工智能·python
用户8356290780514 小时前
自动化文档处理:Python 批量提取 PDF 图片
后端·python
郑州光合科技余经理19 小时前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo12320 小时前
matlab画图工具
开发语言·matlab
dustcell.20 小时前
haproxy七层代理
java·开发语言·前端
norlan_jame20 小时前
C-PHY与D-PHY差异
c语言·开发语言
多恩Stone20 小时前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc