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

相关推荐
jeffer_liu7 小时前
Spring AI 生产级实战:裁判员
java·人工智能·后端·spring·大模型
金銀銅鐵7 小时前
用 Tkinter 实现简单的猜数字游戏
后端·python
copyer_xyf8 小时前
Python 模块与包的导入导出
前端·后端·python
夜微凉48 小时前
三、Spring
java·后端·spring
copyer_xyf8 小时前
Python venv 虚拟环境
前端·后端·python
copyer_xyf10 小时前
Python 如何同时做很多事:进程、线程、协程
前端·后端·python
Full Stack Developme10 小时前
Spring AOP 与 AspectJ
java·后端·spring
IT_陈寒11 小时前
被Vite的动态导入坑了一整天,原来问题出在这
前端·人工智能·后端
码事漫谈11 小时前
你的 AI 编程助手,为什么总在“乱来”?
后端
星浩AI12 小时前
接手 20 万行代码从哪读起?Understand-Anything 把仓库变成可探索的知识图谱
后端·github·claude