惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

A
About on SuperTechFans
C
Cybersecurity and Infrastructure Security Agency CISA
N
News and Events Feed by Topic
C
Cisco Blogs
Cisco Talos Blog
Cisco Talos Blog
A
Arctic Wolf
Scott Helme
Scott Helme
P
Palo Alto Networks Blog
S
Schneier on Security
D
Darknet – Hacking Tools, Hacker News & Cyber Security
T
Tor Project blog
量子位
G
Google Developers Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
B
Blog RSS Feed
NISL@THU
NISL@THU
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
AWS News Blog
AWS News Blog
爱范儿
爱范儿
Last Week in AI
Last Week in AI
Y
Y Combinator Blog
L
LINUX DO - 最新话题
Security Archives - TechRepublic
Security Archives - TechRepublic
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
S
Secure Thoughts
Cloudbric
Cloudbric
aimingoo的专栏
aimingoo的专栏
L
Lohrmann on Cybersecurity
TaoSecurity Blog
TaoSecurity Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Hacker News: Ask HN
Hacker News: Ask HN
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
The GitHub Blog
The GitHub Blog
有赞技术团队
有赞技术团队
S
Security @ Cisco Blogs
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
C
Cyber Attacks, Cyber Crime and Cyber Security
G
GRAHAM CLULEY
P
Proofpoint News Feed
V
V2EX
Martin Fowler
Martin Fowler
C
CERT Recently Published Vulnerability Notes
Attack and Defense Labs
Attack and Defense Labs
C
CXSECURITY Database RSS Feed - CXSecurity.com
The Cloudflare Blog
SecWiki News
SecWiki News
罗磊的独立博客
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
小众软件
小众软件
The Last Watchdog
The Last Watchdog

博客园 - 箫笛

Tkinter - Button 组件 Tkinter - Label 组件 Tkinter - tk 变量 Tkinter - 事件与绑定 Tkinter - 几何管理器 Tkinter - 核心概念 Tkinter - 快速开始 Tkinter - 介绍 Python 编程 - 条件表达式 Python 编程 - 星号下划线参数释义 shell 编程 - shell 脚本的交互方式 Python insall - macOS 系统安装python的几种方式 Miniconda - Python 环境管理工具 Tkinter - Python GUI 开发 Python 编程 - 下划线命名的区别 Python 编程 - 元类编程 Python 编程 - 多重继承与MRO Python 编程 - 描述符协议 Python 编程 - 类型注解 Python 编程 - 生成器表达式 Python 编程 - 集合 Python 编程 - 装饰器 Python 编程 - 闭包 Python 编程 - 列表推导式 Python 编程 - 函数式编程 Python 编程 - lambda 函数 Python 编程 - 文件操作 Python 编程 - 输入与输出 Python 编程 - 面向对象编程 Python 编程 - 字符串(str) Python 编程 - 字典(dict) Python 编程 - 列表(list) Python 编程 - 数据类型和数据结构 Python 编程 - 语句 Python 编程 - 函数 windows - WSL 的安装与使用 shell编程 - dialog 程序使用指南 FE Team - 如何做好前端代码审查 git 提交的撤销和恢复 React15 - redux-saga 如何在saga中实现轮询接口调用? React15 - React CSS Modules BEM命名实践 React15 - React 15 中 componentWillReceiveProps 为什么会多次调用, 同时componentDidUpdate 也会多次调用? React15 - React15类组件多次执行render方法的原因? React15 - React15应用中代码逻辑复用方案 React15 - React状态同步问题解决 React15 - React 15 中 React.pureComponent 的使用场景 React15 - React 15应用在页面渲染时会多次执行类组件的render 函数的原因 React15 - React 15 中能用 componetDidUpdate 代替 componentWillReceiveProps 吗? React15 - React 15 生命周期函数详解 React15 - 如何在React 15中实现自定义的事件订阅与发送(例如组件间通信) React15 - React15应用中的事件订阅和发送机制 React15 - CSS中的BEM规范 React15 - React CSS Modules BEM命名实践 React15 - 写sass 样式文件,嵌套的结构好,还是扁平的结构好? React15 - sass 中 @mixin 和 @extend 的区别是什么? React15 - React 15 应用 如何使用Css moudules 方式进行模块化开发 React15 - React15应用Sass使用指南 React15 - React 15 应用如何进行性能优化?
Python 编程 - 元组(tuple)
箫笛 · 2026-06-20 · via 博客园 - 箫笛

在 Python 3 中,元组(Tuple)是一个不可变的有序元素序列。它是 Python 最基础的数据结构之一,与列表(List)齐名,但核心区别在于创建后不可修改

以下是关于 Python 3 元组最全面的知识点总结,包含大量实用示例:

1. 创建元组

  • 标准语法:使用圆括号 (),元素用逗号隔开。
  • 关键陷阱(单元素元组):必须加尾随逗号,否则 Python 会把它当作普通运算优先级括号。
  • 省略括号:逗号才是元组的真正定义者。
# 空元组
t1 = ()

# 多元素
t2 = (1, 2, 3)

# 重要:单元素元组(必须加逗号)
t3 = (5,)      # 类型为 <class 'tuple'>
t4 = (5)       # 类型为 <class 'int'>,只是整数5

# 省略括号(逗号是关键)
t5 = 1, 2, 3   # 结果 (1, 2, 3)

2. 核心特性:不可变性(Immutable)

这是元组与列表最本质的区别。 一旦创建,你不能增删改其中的元素。

t = (1, 2, 3)
# t[0] = 100  # 会抛出 TypeError: 'tuple' object does not support item assignment

注意:如果元组内的元素是可变对象(如列表),该列表本身可以修改,但元组对该列表的引用(内存地址)不可变。

t = (1, [2, 3])
t[1].append(4)  # 合法!t 变成 (1, [2, 3, 4])

3. 访问与操作

  • 索引:支持正向(0开始)和反向(-1开始)。
  • 切片:返回新的元组。
  • 拼接与重复+*(注意会生成新对象)。
  • 成员检查in / not in
t = (10, 20, 30, 40, 50)
print(t[1])     # 20
print(t[-1])    # 50
print(t[1:4])   # (20, 30, 40)
print(t + (60,)) # (10, 20, 30, 40, 50, 60)
print(20 in t)  # True

4. 内置方法(仅 2 个)

由于不可变,元组的方法极少:

方法 说明
count(x) 统计元素 x 在元组中出现的次数
index(x) 查找元素 x 首次出现的索引(不存在则抛出 ValueError
t = (1, 2, 2, 3)
print(t.count(2))  # 2
print(t.index(3))  # 3

5. 元组打包与解包(核心语法糖)

  • 打包:将多个值赋给一个元组变量。
  • 解包:将元组元素赋值给多个变量。
  • 星号表达式(Python 3 特有):*rest 可以收集剩余元素。
# 打包
data = "Alice", 25, "Engineer"

# 解包(变量数量必须匹配)
name, age, job = data
print(name)  # Alice

# 星号解包(匹配任意长度)
first, *middle, last = (1, 2, 3, 4, 5)
print(first)   # 1
print(middle)  # [2, 3, 4] (注意:结果是列表)
print(last)    # 5

6. 为什么使用元组?(与列表对比)

特性 元组 (Tuple) 列表 (List)
可变性 不可变(线程安全,数据稳定) 可变
内存占用 更小(Python 解释器会做内存优化) 较大
执行速度 创建和访问稍快 稍慢
使用场景 字典的键(Key)、函数返回多值、配置常量 动态数据集合
哈希性 若内部元素均可哈希,则元组本身可哈希 不可哈希,不能作为字典键
# 元组可作为字典键,列表不行
d = {("lat", "lon"): 100}  # 合法
# d = {["lat", "lon"]: 100}  # TypeError

7. 命名元组(NamedTuple)—— 进阶必备

Python 3 的 collections.namedtuple 可以创建带有字段名的元组,兼顾元组的轻量性和类的可读性。Python 3.7+ 还支持类型注解。

from collections import namedtuple

# 定义一个名为 Point 的元组类
Point = namedtuple('Point', ['x', 'y'])
p = Point(10, 20)

print(p.x)    # 10(支持属性访问)
print(p[0])   # 10(支持索引访问)
print(p)      # Point(x=10, y=20)

8. Python 3.11+ 最新特性(类型提示)

在 Python 3.9+ 中,tuple 可以直接用于泛型类型提示;Python 3.11 优化了元组的解包性能。

# 类型注解(Python 3.9+)
def get_user() -> tuple[str, int]:
    return ("Bob", 30)

💡 最佳实践建议

  • 当数据不需要修改时,优先使用元组(更安全、更高效)。
  • 利用解包交换变量:a, b = b, a(底层就是元组打包与解包)。
  • 函数返回多个值时,默认就是元组,可以直接解包接收。