百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 热门文章 > 正文

Introduction to Python Sets 集合介绍

bigegpt 2025-04-30 15:26 21 浏览

What is a Set in Python?

In Python, a set is an unordered (无序的) collection of unique (唯一的) elements. Unlike lists or tuples, sets do not allow duplicate (重复的) values, and their elements have no fixed position. Sets are defined using curly braces {} or the set() function. They are useful for tasks like removing duplicates from a list or checking membership (成员关系) efficiently.

Create a Set

You can create a set in two ways:

  1. Using {} with elements separated by commas:
# A set of fruits (no duplicates)
fruits = {"apple", "banana", "cherry", "apple"}  # "apple" appears only once
print(fruits)  # Output: {'apple', 'banana', 'cherry'}
  1. Using the set() function (useful for converting other data types like lists to sets):
# Convert a list to a set to remove duplicates
numbers = [1, 2, 2, 3, 4, 4, 4]
unique_numbers = set(numbers)
print(unique_numbers)  # Output: {1, 2, 3, 4}

# Create an empty set (note: {} creates a dictionary, not an empty set)
empty_set = set()

Important Features of Sets

  • Unordered: Elements do not have a specific order, so you cannot access them by index.
  • Unique: Each element appears only once; duplicate values are automatically removed.
  • Mutable (可变的): You can add or remove elements after creating the set (but the elements themselves must be immutable, like numbers or strings).

Check if an Element Exists

Use the in keyword to check if an element is present in a set:

fruits = {"apple", "banana", "cherry"}
print("banana" in fruits)  # Output: True
print("grape" in fruits)  # Output: False

Add Elements to a Set

  • add(): Adds a single element to the set.
fruits = {"apple", "banana"}
fruits.add("cherry")
print(fruits)  # Output: {'apple', 'banana', 'cherry'}
  • update(): Adds multiple elements (from another set, list, or tuple).
vegetables = {"carrot", "potato"}
fruits.update(vegetables)  # Add all elements from vegetables set
fruits.update(["orange", "grape"])  # Add elements from a list
print(fruits)  # Output: {'apple', 'banana', 'cherry', 'carrot', 'potato', 'orange', 'grape'}

Remove Elements from a Set

  • remove(value): Removes a specific element; raises an error if the element does not exist.
fruits = {"apple", "banana", "cherry"}
fruits.remove("banana")
print(fruits)  # Output: {'apple', 'cherry'}
# fruits.remove("grape")  # This will cause a KeyError
  • discard(value): Removes an element if it exists; does nothing if the element is not found.
fruits.discard("grape")  # No error even if "grape" is not present
  • pop(): Removes and returns a random element (since sets are unordered, the removed element is unpredictable).
random_fruit = fruits.pop()
print(random_fruit)  # Output: e.g., 'apple' (varies each time)
print(fruits)  # Output: {'cherry'} (if 'apple' was removed)
  • clear(): Removes all elements from the set.
fruits.clear()
print(fruits)  # Output: set()

Set Operations

Sets support mathematical operations like union (并集), intersection (交集), difference (差集), and symmetric difference (对称差集).

  1. Union (∪): Combines elements from two sets (duplicates removed).
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)  # or set1 | set2
print(union_set)  # Output: {1, 2, 3, 4, 5}
  1. Intersection (∩): Returns elements common to both sets.
intersection_set = set1.intersection(set2)  # or set1 & set2
print(intersection_set)  # Output: {3}
  1. Difference (-): Returns elements in the first set but not in the second.
difference_set = set1.difference(set2)  # or set1 - set2
print(difference_set)  # Output: {1, 2} (elements in set1 but not set2)
  1. Symmetric Difference (⊕): Returns elements in either set but not in both.
symmetric_diff_set = set1.symmetric_difference(set2)  # or set1 ^ set2
print(symmetric_diff_set)  # Output: {1, 2, 4, 5}

Loop Through a Set

You can use a for loop to iterate over the elements in a set (order is not guaranteed):

fruits = {"apple", "banana", "cherry"}
for fruit in fruits:
    print(fruit)

Possible output (order may vary):

banana
apple
cherry

Set vs. List vs. Tuple: Key Differences

Feature

Set

List

Tuple

Order (顺序)

Unordered

Ordered

Ordered

Duplicates (重复项)

Not allowed

Allowed

Allowed

Mutability (可变性)

Mutable (can add/remove items)

Mutable

Immutable

Syntax (语法)

{} or set()

[]

()

Use Cases

Remove duplicates, membership checks

Dynamic lists, ordered data

Fixed records, fast iteration

Example: Practical Use of Sets

Use Case 1: Remove Duplicates from a List
Suppose you have a list of scores with duplicates and want unique values:

scores = [85, 90, 85, 95, 90, 85]
unique_scores = set(scores)
print(unique_scores)  # Output: {85, 90, 95}

Use Case 2: Find Common Students in Two Classes

class1 = {"Alice", "Bob", "Charlie"}
class2 = {"Bob", "David", "Eve"}
common_students = class1.intersection(class2)
print(common_students)  # Output: {"Bob"}

Python集合介绍

什么是Python中的集合?

在Python中,**集合(set)**是一种无序的(unordered)唯一元素(unique elements)集合。与列表或元组不同,集合不允许重复(duplicate)值,且元素没有固定顺序。集合用花括号{}或set()函数定义。它们适用于从列表中删除重复项或高效检查成员关系(membership)等任务。

创建集合

创建集合有两种方式:

  1. 使用{}并以逗号分隔元素:
# 水果集合(无重复项)
fruits = {"apple", "banana", "cherry", "apple"}  # "apple"仅出现一次
print(fruits)  # 输出:{'apple', 'banana', 'cherry'}
  1. 使用set()函数(适用于将列表等其他数据类型转换为集合):
# 将列表转换为集合以删除重复项
numbers = [1, 2, 2, 3, 4, 4, 4]
unique_numbers = set(numbers)
print(unique_numbers)  # 输出:{1, 2, 3, 4}

# 创建空集合(注意:{}创建的是字典,不是空集合)
empty_set = set()

集合的重要特性

  • 无序性:元素没有特定顺序,因此不能通过索引访问。
  • 唯一性:每个元素仅出现一次,重复值会被自动删除。
  • 可变性(Mutable):可以在创建后添加或删除元素(但元素本身必须是不可变的,如数字或字符串)。

检查元素是否存在

使用in关键字检查元素是否在集合中:

fruits = {"apple", "banana", "cherry"}
print("banana" in fruits)  # 输出:True
print("grape" in fruits)  # 输出:False

向集合中添加元素

  • add():向集合中添加单个元素。
fruits = {"apple", "banana"}
fruits.add("cherry")
print(fruits)  # 输出:{'apple', 'banana', 'cherry'}
  • update():添加多个元素(来自另一个集合、列表或元组)。
vegetables = {"carrot", "potato"}
fruits.update(vegetables)  # 添加vegetables集合中的所有元素
fruits.update(["orange", "grape"])  # 添加列表中的元素
print(fruits)  # 输出:{'apple', 'banana', 'cherry', 'carrot', 'potato', 'orange', 'grape'}

从集合中删除元素

  • remove(value):删除指定元素;若元素不存在则抛出错误。
fruits = {"apple", "banana", "cherry"}
fruits.remove("banana")
print(fruits)  # 输出:{'apple', 'cherry'}
# fruits.remove("grape")  # 这会导致KeyError错误
  • discard(value):若元素存在则删除;若不存在则不执行任何操作。
fruits.discard("grape")  # 即使"grape"不存在也不会报错
  • pop():删除并返回一个随机元素(由于集合无序,删除的元素不可预测)。
random_fruit = fruits.pop()
print(random_fruit)  # 输出:例如'apple'(每次运行结果可能不同)
print(fruits)  # 输出:{'cherry'}(假设删除了'apple')
  • clear():清空集合中的所有元素。
fruits.clear()
print(fruits)  # 输出:set()

集合运算

集合支持并集(union)、交集(intersection)、差集(difference)和对称差集(symmetric difference)等数学运算。

  1. 并集(∪):合并两个集合的元素(去除重复项)。
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)  # 或 set1 | set2
print(union_set)  # 输出:{1, 2, 3, 4, 5}
  1. 交集(∩):返回两个集合的共同元素。
intersection_set = set1.intersection(set2)  # 或 set1 & set2
print(intersection_set)  # 输出:{3}
  1. 差集(-):返回第一个集合中存在但第二个集合中不存在的元素。
difference_set = set1.difference(set2)  # 或 set1 - set2
print(difference_set)  # 输出:{1, 2}(set1中有但set2中没有的元素)
  1. 对称差集(⊕):返回在任一集合中存在但不同时存在的元素。
symmetric_diff_set = set1.symmetric_difference(set2)  # 或 set1 ^ set2
print(symmetric_diff_set)  # 输出:{1, 2, 4, 5}

遍历集合

可以使用for循环遍历集合中的元素(顺序不固定):

fruits = {"apple", "banana", "cherry"}
for fruit in fruits:
    print(fruit)

可能的输出(顺序可能不同):

banana
apple
cherry

集合 vs. 列表 vs. 元组:主要区别

特性

集合(Set)

列表(List)

元组(Tuple)

顺序(Order)

无序(Unordered)

有序(Ordered)

有序(Ordered)

重复项(Duplicates)

不允许(Not allowed)

允许(Allowed)

允许(Allowed)

可变性(Mutability)

可变(可添加/删除元素)

可变(Mutable)

不可变(Immutable)

语法(Syntax)

{} 或 set()

[]

()

使用场景

去重、成员检查

动态列表、有序数据

固定记录、快速遍历

示例:集合的实际应用

场景1:从列表中删除重复项
假设你有一个包含重复分数的列表,需要获取唯一值:

scores = [85, 90, 85, 95, 90, 85]
unique_scores = set(scores)
print(unique_scores)  # 输出:{85, 90, 95}

场景2:查找两个班级的共同学生

class1 = {"Alice", "Bob", "Charlie"}
class2 = {"Bob", "David", "Eve"}
common_students = class1.intersection(class2)
print(common_students)  # 输出:{"Bob"}

专业词汇和不常用词汇表

set, /set/, 集合
unordered, /n'rdrd/, 无序的
unique, /ju'nik/, 唯一的
duplicate, /'duplket/, 重复的
membership, /'membrp/, 成员关系
mutable, /'mjutbl/, 可变的
union, /'junin/, 并集
intersection, /ntr'sekn/, 交集
difference, /'dfrns/, 差集
symmetric difference, /s'metrk 'dfrns/, 对称差集
iterate, /'tret/, 遍历

相关推荐

或者这些Joplin插件也可以帮助你的笔记应用再一次强大

写在前面距离上次分享《搭建私有全平台多端同步笔记,群晖NAS自建JoplinServer服务》已过去一段时间,大家是否开始使用起来了呢?如果你和我一样已经使用过Joplin有一段时间了,那或许你也会...

Three.JS教程4 threejs中的辅助类

一、辅助类简介Three.js提供了一些辅助类(Helpers)以帮助我们更容易地调试、可视化场景中的元素。ArrowHelepr:创建箭头辅助器;AxisHelper:创建坐标轴辅助器;BoxH...

第2章 还记得点、线、面吗(二)(第二章还能敲钟吗)

glbgltf模型(webvrmodel)-gltf模型下载定制,glb模型下载定制,三维项目电商网站在线三维展示,usdz格式,vr模型网,网页VR模型下载,三维模型下载,webgl网页模型下载我...

如何检查Linux系统硬件信息?从CPU到显卡,一网打尽!

你可能会问:“我为什么要关心硬件信息?”答案很简单:硬件是Linux系统的根基,了解它可以帮你解决很多实际问题。比如:性能调优:知道CPU核心数和内存大小,才能更好地调整程序运行参数。故障排查:系统卡...

SpriteJS:图形库造轮子的那些事儿

从2017年到2020年,我花了大约4年的时间,从零到一,实现了一个可切换WebGL和Canvas2D渲染的,跨平台支持浏览器、SSR、小程序,基于DOM结构和支持响应式的,高...

平时积累的FPGA知识点(6)(fpga经典应用100例)

平时在FPGA群聊等积累的FPGA知识点,第六期:1万兆网接口,发三十万包,会出现掉几包的情况,为什么?原因:没做时钟约束,万兆网接口的实现,本质上都是高速serdes,用IP的话,IP会自带约束。...

芯片逻辑调度框架设计 都需要那些那些软件工具

设计芯片逻辑调度框架通常需要使用以下软件工具:1.逻辑设计工具:例如Vivado、Quartus、SynopsysDesignCompiler等,用于设计和实现逻辑电路。2.仿真工具:例如Mo...

ZYNQ与DSP之间EMIF16通信(正点原子领航者zynq之fpga开发指南v3)

本文主要介绍说明XQ6657Z35-EVM高速数据处理评估板ZYNQ与DSP之间EMIF16通信的功能、使用步骤以及各个例程的运行效果。[基于TIKeyStone架构C6000系列TMS320C6...

好课推荐:从零开始大战FPGA(从零开始的冒险4399)

从零开始大战FPGA引子:本课程为“从零开始大战FPGA”系列课程的基础篇。课程通俗易懂、逻辑性强、示例丰富,课程中尤其强调在设计过程中对“时序”和“逻辑”的把控,以及硬件描述语言与硬件电路相对应的“...

业界第一个真正意义上开源100 Gbps NIC Corundum介绍

来源:内容由「网络交换FPGA」编译自「FCCM2020」,谢谢。FCCM2020在5月4日开始线上举行,对外免费。我们有幸聆听了其中一个有关100G开源NIC的介绍,我们对该文章进行了翻译,并对其中...

高层次综合:解锁FPGA广阔应用的最后一块拼图

我们为什么需要高层次综合高层次综合(High-levelSynthesis)简称HLS,指的是将高层次语言描述的逻辑结构,自动转换成低抽象级语言描述的电路模型的过程。所谓的高层次语言,包括C、C++...

Xilinx文档编号及其内容索引(部分)

Xilinx文档的数量非常多。即使全职从事FPGA相关工作,没有几年时间不可能对器件特性、应用、注意事项等等有较为全面的了解。本文记录了我自使用Xilinx系列FPGA以来或精读、或翻阅、或查询过的文...

Xilinx Vivado联合Modelsim软件仿真

引言:Xilinx公司Vivado开发软件自带仿真工具,可以实现一般性能的FPGA软件仿真测试,其测试执行效率以及性能都不如第三方专用仿真软件Modelsim强。本文我们介绍下如何进行Vivado20...

体育动画直播是怎么做出来的?从数据到虚拟赛场的科技魔法!

你是否见过这样的比赛直播?没有真实球员,却能看梅西带球突破?足球比赛变成动画版,但数据100%真实?电竞比赛用虚拟形象直播,选手操作实时同步?这就是体育动画直播——一种融合实时数据、游戏引擎和AI的...

Dialogue between CPC and political parties of neighboring countries held in Beijing

BEIJING,May26(Xinhua)--TheCommunistPartyofChina(CPC)inDialoguewithPoliticalPartiesof...