Introduction to Python Sets 集合介绍
bigegpt 2025-04-30 15:26 24 浏览
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:
- 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'}
- 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 (对称差集).
- 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}
- Intersection (∩): Returns elements common to both sets.
intersection_set = set1.intersection(set2) # or set1 & set2
print(intersection_set) # Output: {3}
- 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)
- 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)等任务。
创建集合
创建集合有两种方式:
- 使用{}并以逗号分隔元素:
# 水果集合(无重复项)
fruits = {"apple", "banana", "cherry", "apple"} # "apple"仅出现一次
print(fruits) # 输出:{'apple', 'banana', 'cherry'}
- 使用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)等数学运算。
- 并集(∪):合并两个集合的元素(去除重复项)。
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2) # 或 set1 | set2
print(union_set) # 输出:{1, 2, 3, 4, 5}
- 交集(∩):返回两个集合的共同元素。
intersection_set = set1.intersection(set2) # 或 set1 & set2
print(intersection_set) # 输出:{3}
- 差集(-):返回第一个集合中存在但第二个集合中不存在的元素。
difference_set = set1.difference(set2) # 或 set1 - set2
print(difference_set) # 输出:{1, 2}(set1中有但set2中没有的元素)
- 对称差集(⊕):返回在任一集合中存在但不同时存在的元素。
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/, 遍历
相关推荐
- 方差分析简介(方差分析通俗理解)
-
介绍方差分析(ANOVA,AnalysisofVariance)是一种广泛使用的统计方法,用于比较两个或多个组之间的均值。单因素方差分析是方差分析的一种变体,旨在检测三个或更多分类组的均值是否存在...
- 正如404页面所预示,猴子正成为断网元凶--吧嗒吧嗒真好吃
-
吧嗒吧嗒,绘图:MakiNaro你可以通过加热、冰冻、水淹、模塑、甚至压溃压力来使网络光缆硬化。但用猴子显然是不行的。光缆那新挤压成型的塑料外皮太尼玛诱人了,无法阻挡一场试吃盛宴的举行。印度政府正...
- Python数据可视化:箱线图多种库画法
-
概念箱线图通过数据的四分位数来展示数据的分布情况。例如:数据的中心位置,数据间的离散程度,是否有异常值等。把数据从小到大进行排列并等分成四份,第一分位数(Q1),第二分位数(Q2)和第三分位数(Q3)...
- 多组独立(完全随机设计)样本秩和检验的SPSS操作教程及结果解读
-
作者/风仕在上一期,我们已经讲完了两组独立样本秩和检验的SPSS操作教程及结果解读,这期开始讲多组独立样本秩和检验,我们主要从多组独立样本秩和检验介绍、两组独立样本秩和检验使用条件及案例的SPSS操作...
- 方差分析 in R语言 and Excel(方差分析r语言例题)
-
今天来写一篇实际中比较实用的分析方法,方差分析。通过方差分析,我们可以确定组别之间的差异是否超出了由于随机因素引起的差异范围。方差分析分为单因素方差分析和多因素方差分析,这一篇先介绍一下单因素方差分析...
- 可视化:前端数据可视化插件大盘点 图表/图谱/地图/关系图
-
前端数据可视化插件大盘点图表/图谱/地图/关系图全有在大数据时代,很多时候我们需要在网页中显示数据统计报表,从而能很直观地了解数据的走向,开发人员很多时候需要使用图表来表现一些数据。随着Web技术的...
- matplotlib 必知的 15 个图(matplotlib各种图)
-
施工专题,我已完成20篇,施工系列几乎覆盖Python完整技术栈,目标只总结实践中最实用的东西,直击问题本质,快速帮助读者们入门和进阶:1我的施工计划2数字专题3字符串专题4列表专题5流程控制专题6编...
- R ggplot2常用图表绘制指南(ggplot2绘制折线图)
-
ggplot2是R语言中强大的数据可视化包,基于“图形语法”(GrammarofGraphics),通过分层方式构建图表。以下是常用图表命令的详细指南,涵盖基本语法、常见图表类型及示例,适合...
- Python数据可视化:从Pandas基础到Seaborn高级应用
-
数据可视化是数据分析中不可或缺的一环,它能帮助我们直观理解数据模式和趋势。本文将全面介绍Python中最常用的三种可视化方法。Pandas内置绘图功能Pandas基于Matplotlib提供了简洁的绘...
- Python 数据可视化常用命令备忘录
-
本文提供了一个全面的Python数据可视化备忘单,适用于探索性数据分析(EDA)。该备忘单涵盖了单变量分析、双变量分析、多变量分析、时间序列分析、文本数据分析、可视化定制以及保存与显示等内容。所...
- 统计图的种类(统计图的种类及特点图片)
-
统计图是利用几何图形或具体事物的形象和地图等形式来表现社会经济现象数量特征和数量关系的图形。以下是几种常见的统计图类型及其适用场景:1.条形图(BarChart)条形图是用矩形条的高度或长度来表示...
- 实测,大模型谁更懂数据可视化?(数据可视化和可视化分析的主要模型)
-
大家好,我是Ai学习的老章看论文时,经常看到漂亮的图表,很多不知道是用什么工具绘制的,或者很想复刻类似图表。实测,大模型LaTeX公式识别,出乎预料前文,我用Kimi、Qwen-3-235B...
- 通过AI提示词让Deepseek快速生成各种类型的图表制作
-
在数据分析和可视化领域,图表是传达信息的重要工具。然而,传统图表制作往往需要专业的软件和一定的技术知识。本文将介绍如何通过AI提示词,利用Deepseek快速生成各种类型的图表,包括柱状图、折线图、饼...
- 数据可视化:解析箱线图(box plot)
-
箱线图/盒须图(boxplot)是数据分布的图形表示,由五个摘要组成:最小值、第一四分位数(25th百分位数)、中位数、第三四分位数(75th百分位数)和最大值。箱子代表四分位距(IQR)。IQR是...
- [seaborn] seaborn学习笔记1-箱形图Boxplot
-
1箱形图Boxplot(代码下载)Boxplot可能是最常见的图形类型之一。它能够很好表示数据中的分布规律。箱型图方框的末尾显示了上下四分位数。极线显示最高和最低值,不包括异常值。seaborn中...
- 一周热门
- 最近发表
- 标签列表
-
- mybatiscollection (79)
- mqtt服务器 (88)
- keyerror (78)
- c#map (65)
- xftp6 (83)
- bt搜索 (75)
- c#var (76)
- xcode-select (66)
- mysql授权 (74)
- 下载测试 (70)
- linuxlink (65)
- pythonwget (67)
- androidinclude (65)
- libcrypto.so (74)
- linux安装minio (74)
- ubuntuunzip (67)
- vscode使用技巧 (83)
- secure-file-priv (67)
- vue阻止冒泡 (67)
- jquery跨域 (68)
- php写入文件 (73)
- kafkatools (66)
- mysql导出数据库 (66)
- jquery鼠标移入移出 (71)
- 取小数点后两位的函数 (73)