Python 中的 `set` 数据结构:介绍与使用(1)

简介

set 是 Python 中用于存储无序且不重复元素的数据结构。set 是可变的,但其中存储的元素必须是不可变类型。

创建集合

创建集合最简单的方法是使用花括号 {}

python 复制代码
my_set = {1, 2, 3, 4, 5}

也可以使用内置的 set() 函数来创建集合。

python 复制代码
another_set = set([6, 7, 8, 9, 10])

常用操作

添加元素

  • add(): 向集合添加一个元素。

    python 复制代码
    my_set.add(6)
  • update(): 向集合添加多个元素。

    python 复制代码
    my_set.update([7, 8, 9])

删除元素

  • remove(): 删除集合中的指定元素。

    python 复制代码
    my_set.remove(1)
  • discard(): 删除集合中的指定元素,如果元素不存在,不会引发错误。

    python 复制代码
    my_set.discard(10)
  • pop(): 删除并返回集合中的一个随机元素。

    python 复制代码
    item = my_set.pop()
  • clear(): 删除集合中的所有元素。

    python 复制代码
    my_set.clear()

集合运算

  • union(): 返回两个集合的并集。

    python 复制代码
    union_set = my_set.union(another_set)
  • intersection(): 返回两个集合的交集。

    python 复制代码
    intersection_set = my_set.intersection(another_set)
  • difference(): 返回两个集合的差集。

    python 复制代码
    difference_set = my_set.difference(another_set)
  • symmetric_difference(): 返回两个集合的对称差集。

    python 复制代码
    symmetric_difference_set = my_set.symmetric_difference(another_set)

集合推导式

集合推导式提供了一种简洁的创建集合的方式。

python 复制代码
squares = {x*x for x in range(10)}

总结

Python 的 set 数据结构提供了一种灵活且高效的方式来存储和操作无序且不重复的元素集。它提供了多种内置方法,以方便地进行集合运算和元素操作。

相关推荐
Moment6 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
Cobyte7 小时前
AI全栈实战:使用 Python+LangChain+Vue3 构建一个 LLM 聊天应用
前端·后端·aigc
程序员侠客行7 小时前
Mybatis连接池实现及池化模式
java·后端·架构·mybatis
Honmaple7 小时前
QMD (Quarto Markdown) 搭建与使用指南
后端
PP东8 小时前
Flowable学习(二)——Flowable概念学习
java·后端·学习·flowable
invicinble8 小时前
springboot的核心实现机制原理
java·spring boot·后端
全栈老石8 小时前
Python 异步生存手册:给被 JS async/await 宠坏的全栈工程师
后端·python
space62123278 小时前
在SpringBoot项目中集成MongoDB
spring boot·后端·mongodb
Tony Bai9 小时前
再见,丑陋的 container/heap!Go 泛型堆 heap/v2 提案解析
开发语言·后端·golang
寻找奶酪的mouse10 小时前
30岁技术人对职业和生活的思考
前端·后端·年终总结