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

Introduction to Python Sets 集合介绍

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

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/, 遍历

相关推荐

当Frida来“敲”门(frida是什么)

0x1渗透测试瓶颈目前,碰到越来越多的大客户都会将核心资产业务集中在统一的APP上,或者对自己比较重要的APP,如自己的主业务,办公APP进行加壳,流量加密,投入了很多精力在移动端的防护上。而现在挖...

服务端性能测试实战3-性能测试脚本开发

前言在前面的两篇文章中,我们分别介绍了性能测试的理论知识以及性能测试计划制定,本篇文章将重点介绍性能测试脚本开发。脚本开发将分为两个阶段:阶段一:了解各个接口的入参、出参,使用Python代码模拟前端...

Springboot整合Apache Ftpserver拓展功能及业务讲解(三)

今日分享每天分享技术实战干货,技术在于积累和收藏,希望可以帮助到您,同时也希望获得您的支持和关注。架构开源地址:https://gitee.com/msxyspringboot整合Ftpserver参...

Linux和Windows下:Python Crypto模块安装方式区别

一、Linux环境下:fromCrypto.SignatureimportPKCS1_v1_5如果导包报错:ImportError:Nomodulenamed'Crypt...

Python 3 加密简介(python des加密解密)

Python3的标准库中是没多少用来解决加密的,不过却有用于处理哈希的库。在这里我们会对其进行一个简单的介绍,但重点会放在两个第三方的软件包:PyCrypto和cryptography上,我...

怎样从零开始编译一个魔兽世界开源服务端Windows

第二章:编译和安装我是艾西,上期我们讲述到编译一个魔兽世界开源服务端环境准备,那么今天跟大家聊聊怎么编译和安装我们直接进入正题(上一章没有看到的小伙伴可以点我主页查看)编译服务端:在D盘新建一个文件夹...

附1-Conda部署安装及基本使用(conda安装教程)

Windows环境安装安装介质下载下载地址:https://www.anaconda.com/products/individual安装Anaconda安装时,选择自定义安装,选择自定义安装路径:配置...

如何配置全世界最小的 MySQL 服务器

配置全世界最小的MySQL服务器——如何在一块IntelEdison为控制板上安装一个MySQL服务器。介绍在我最近的一篇博文中,物联网,消息以及MySQL,我展示了如果Partic...

如何使用Github Action来自动化编译PolarDB-PG数据库

随着PolarDB在国产数据库领域荣膺桂冠并持续获得广泛认可,越来越多的学生和技术爱好者开始关注并涉足这款由阿里巴巴集团倾力打造且性能卓越的关系型云原生数据库。有很多同学想要上手尝试,却卡在了编译数据...

面向NDK开发者的Android 7.0变更(ndk android.mk)

订阅Google官方微信公众号:谷歌开发者。与谷歌一起创造未来!受Android平台其他改进的影响,为了方便加载本机代码,AndroidM和N中的动态链接器对编写整洁且跨平台兼容的本机...

信创改造--人大金仓(Kingbase)数据库安装、备份恢复的问题纪要

问题一:在安装KingbaseES时,安装用户对于安装路径需有“读”、“写”、“执行”的权限。在Linux系统中,需要以非root用户执行安装程序,且该用户要有标准的home目录,您可...

OpenSSH 安全漏洞,修补操作一手掌握

1.漏洞概述近日,国家信息安全漏洞库(CNNVD)收到关于OpenSSH安全漏洞(CNNVD-202407-017、CVE-2024-6387)情况的报送。攻击者可以利用该漏洞在无需认证的情况下,通...

Linux:lsof命令详解(linux lsof命令详解)

介绍欢迎来到这篇博客。在这篇博客中,我们将学习Unix/Linux系统上的lsof命令行工具。命令行工具是您使用CLI(命令行界面)而不是GUI(图形用户界面)运行的程序或工具。lsoflsof代表&...

幻隐说固态第一期:固态硬盘接口类别

前排声明所有信息来源于网络收集,如有错误请评论区指出更正。废话不多说,目前固态硬盘接口按速度由慢到快分有这几类:SATA、mSATA、SATAExpress、PCI-E、m.2、u.2。下面我们来...

新品轰炸 影驰SSD多款产品登Computex

分享泡泡网SSD固态硬盘频道6月6日台北电脑展作为全球第二、亚洲最大的3C/IT产业链专业展,吸引了众多IT厂商和全球各地媒体的热烈关注,全球存储新势力—影驰,也积极参与其中,为广大玩家朋友带来了...