Introduction to Python Sets 集合介绍
bigegpt 2025-04-30 15:26 22 浏览
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/, 遍历
相关推荐
- 恢复软件6款汇总推荐,帮你减轻数据恢复压力!
-
在当今数字化生活中,数据丢失的风险如影随形。无论是误删文件、硬盘故障,还是遭遇病毒攻击,丢失的数据都可能给我们带来不小的麻烦。此时,一款优秀的数据恢复软件就成为了挽救数据的关键。今天,为大家汇总推荐...
- 中兴星星一号刷回官方原版recovery的教程
-
【搞科技教程】中兴星星一号的官方recovery也来说一下了,因为之前给大家分享过了第三方的recovery了,之前给大家分享的第三方recovery也是采用一键刷入的方式,如果细心的朋友会发现,之前...
- 新玩机工具箱,Uotan柚坛工具箱软件体验
-
以前的手机系统功能比较单调,各厂商的重视程度不一样,所以喜欢玩机的朋友会解锁手机系统的读写权限,来进行刷机或者ROOT之类的操作,让使用体验更好。随着现在的手机系统越来越保守,以及自身功能的增强,...
- 三星g906k刷recovery教程_三星g906k中文recovery下载
-
【搞科技教程】看到有一些机友在找三星g906k的第三方recovery,下面就来说一下详细的recovery的刷入方法了,因为手机只有有了第三方的recovery之后才可以刷第三方的root包和系统包...
- 中兴星星2号刷recovery教程_星星二号中文recovery下载
-
【搞科技教程】咱们的中兴星星2手机也就是中兴星星二号手机的第三方recovery已经出来了,并且是中文版的,有了这个recovery之后,咱们的手机就可以轻松的刷第三方的系统包了,如果没有第三方的re...
- 数据恢复软件有哪些值得推荐?这 6 款亲测好用的工具汇总请收好!
-
在数字生活中,数据丢失的阴霾常常突如其来。无论是误删工作文档、格式化重要磁盘,还是遭遇系统崩溃,都可能让我们陷入焦虑。关键时刻,一款得力的数据恢复软件便是那根“救命稻草”。今天,为大家精心汇总6...
- 中兴u956刷入recovery的教程(中兴e5900刷机)
-
【搞科技教程】这次主要来给大家说说中兴u956手机如何刷入第三方的recovery,因为第三方的recovery工具是咱们刷第三方rom包的基础,可是很我欠却不会刷,所以太这里来给大家整理了一下详细的...
- 联想A850+刷recovery教程 联想A850+第三方recovery下载
-
【搞科技教程】联想A850+的第三方recovery出来了,这个第三方的recovery是非常的重要的,比如咱们的手机要刷第三方的系统包的时候,都是需要用到这个第三方的recovery的,在网上也是有...
- 工具侠重大更新 智能机上刷机一条龙完成
-
工具侠是针对玩机的机油开发的一款工具,不管是发烧级别的粉丝,还是普通小白用户,都可以在工具侠上找到你喜欢的工具应用。这不,最新的工具侠2.0.16版本,更新了专门为小白准备的刷机助手工具,以及MTK超...
- shift+delete删除的文件找回6种硬盘数据恢复工具
-
硬盘作为电脑的重要存储设备,如同一个巨大的数字仓库,承载着我们日常工作、学习和生活中的各种文件,从珍贵的照片、重要的工作文档到喜爱的视频、音乐等,都依赖硬盘来安全存放。但有时,我们可能会不小心用sh...
- 使用vscode+Deepseek 实现AI编程 基于Cline和continue
-
尊敬的诸位!我是一名专注于嵌入式开发的物联网工程师。关注我,持续分享最新物联网与AI资讯和开发实战。期望与您携手探寻物联网与AI的无尽可能。这两天deepseek3.0上线,据说编程能力比肩Cl...
- 详解如何使用VSCode搭建TypeScript环境(适合小白)
-
搭建Javascript环境因为TypeScript不能直接在浏览器上运行。它需要编译器来编译并生成JavaScript文件。所以需要首先安装好javascript环境,可以参考文章:https://...
- 使用VSCode来书写你的Jupyter Notebooks
-
现在你可以在VScode里面来书写你的notebook了,使用起来十分的方便。下面来给大家演示一下环境的搭建。首先需要安装一个jupyter的包,使用下面的命令安装:pip3install-ih...
- 使用VSCode模板提高Vue开发效率(vscode开发vue插件)
-
安装VSCode安装Vetur和VueHelper插件,安装完成后需要重启VScode。在扩展插件搜索框中找到如下Vetur和VueHelper两个插件,注意看图标。添加Vue模板打...
- 干货!VsCode接入DeepSeek实现AI编程的5种主流插件详解
-
AI大模型对编程的影响非常之大,可以说首当其冲,Cursor等对话式编程工具渐渐渗透到开发者的工作中,作为AI编程的明星产品,Cursor虽然好用,但是贵啊,所以咱们得找平替,最好免费那种。俗话说,不...
- 一周热门
- 最近发表
- 标签列表
-
- 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)
- logstashinput (65)
- vue阻止冒泡 (67)
- jquery跨域 (68)
- php写入文件 (73)
- kafkatools (66)
- mysql导出数据库 (66)
- jquery鼠标移入移出 (71)
- 取小数点后两位的函数 (73)