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)

集合方法

相关推荐
渔阳节度使1 小时前
SpringAI实时监控+观测性
后端·python·flask
铁手飞鹰1 小时前
Visual Studio创建Cmake工程导出DLL,通过Python调用DLL
android·python·visual studio
飞Link1 小时前
告别盲目找Bug:深度解析 TSTD 异常检测中的预测模型(Python 实战版)
开发语言·python·算法·bug
1.14(java)1 小时前
Spring-boot快速上手
java·开发语言·javaee
7yewh1 小时前
jetson_yolo_deployment 02_linux_dev_skills
linux·python·嵌入式硬件·yolo·嵌入式
记忆多2 小时前
c++名字空间 函数模版 左右值
开发语言·c++·算法
love530love3 小时前
ComfyUI rgthree-comfy Image Comparer 节点无输出问题排查与解决
人工智能·windows·python·comfyui·rgthree-comfy·nodes 2.0·vue 节点
2401_889884663 小时前
高性能计算通信库
开发语言·c++·算法
badhope3 小时前
Docker从零开始安装配置全攻略
运维·人工智能·vscode·python·docker·容器·github
用户0332126663673 小时前
使用 Python 复制 Excel 工作表
python