Python元组常用操作方法

元组是Python中不可变的有序序列,与列表类似但创建后不能修改。以下是元组的常用操作方法:

1. 创建元组

python 复制代码
# 空元组
empty_tuple = ()

# 单元素元组(注意逗号)
single_tuple = (1,)  # 必须有逗号,否则不是元组

# 多元素元组
my_tuple = (1, 2, 3, 'a', 'b')
print(my_tuple)
# (1, 2, 3, 'a', 'b')

another_tuple = tuple([1, 2, 3])  # 从列表转换
print(another_tuple)
# (1, 2, 3)

2. 基本操作

python 复制代码
t = (1, 2, 3, 4, 5)

# 索引访问
print(t[0])  # 输出: 1

# 切片操作
print(t[1:3])  # 输出: (2, 3)

# 长度
print(len(t))  # 输出: 5

# 连接元组
new_t = t + (6, 7)
print(new_t)  # 输出: (1, 2, 3, 4, 5, 6, 7)

# 重复元组
repeat_t = t * 2
print(repeat_t)  # 输出: (1, 2, 3, 4, 5, 1, 2, 3, 4, 5)

3. 元组方法

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

python 复制代码
t = (1, 2, 2, 3, 4)

# count() - 统计元素出现次数
print(t.count(2))  # 输出: 2

# index() - 返回元素第一次出现的索引
print(t.index(3))  # 输出: 3

4. 元组解包

python 复制代码
# 基本解包
a, b, c = (1, 2, 3)
print(a, b, c)  # 输出: 1 2 3

# 使用*收集剩余元素
first, *middle, last = (1, 2, 3, 4, 5)
print(first)    # 输出: 1
print(middle)   # 输出: [2, 3, 4]
print(last)     # 输出: 5

5. 元组转换

python 复制代码
# 列表转元组
arr = [1, 2, 3]
t = tuple(arr)
print(t) # (1, 2, 3)

# 元组转列表
new_list = list(t)
print(new_list) # [1, 2, 3]

6. 遍历元组

python 复制代码
t = (1, 2, 3, 4)

# 直接遍历
for item in t:
    print(item) # 1,2,3,4

# 带索引遍历
for index, value in enumerate(t):
    print(f"Index: {index}, Value: {value}")
    # Index: 0, Value: 1
    # Index: 1, Value: 2
    # Index: 2, Value: 3
    # Index: 3, Value: 4

7. 元组作为字典键

由于元组不可变,可以作为字典的键:

python 复制代码
locations = {
    (35.6895, 39.6917): "Tokyo",
    (40.7128, 74.0060): "New York"
}

8. 不可变性说明

元组一旦创建,不能修改其内容:

python 复制代码
t = (1, 2, 3)
# t[0] = 10  # 会引发TypeError

但若元组包含可变对象(如列表),这些可变对象可以修改:

python 复制代码
t = (1, [2, 3], 4)
t[1].append(5)  # 可以,因为修改的是列表
print(t)  # 输出: (1, [2, 3, 5], 4)

元组的不可变性使其适合用作字典键或在需要保证数据不被修改的场景中使用。

相关推荐
染指11108 分钟前
162.Agent-LangGraph-检查点的作用
人工智能·python·langchain·agents
我命由我1234527 分钟前
访客系统形式(有用户概念、无用户概念)
java·开发语言·前端·javascript·python·产品运营·产品经理
xixingzhe242 分钟前
图表中同比与环比的区别:看趋势还是看变化?
开发语言·python
forest_091 小时前
当 AI 搜索开始「自我进化」,谁来进化它的核实?——「已核实」结论复核器:3 条结论挖出 2 个洞(附可运行代码)
人工智能·python·机器学习·prompt·agi
小小张说故事1 小时前
Python 的 str 为什么设计成不可变?拆开字符串驻留、字符串池,以及 += 拼接到底慢在哪
后端·python
ljt27249606611 小时前
Python笔记(十一)--Numpy(一)
笔记·python·numpy
时早玖沐1 小时前
KOOK「找不到语音频道」:同一个错误假设,我犯了三次
python·开源·ai编程
_冷眸_1 小时前
Python 调用大模型 API:最小请求、Base URL 和 401/404 排查
开发语言·人工智能·python
Dumbness2 小时前
UIA 读微信群消息没有 id,怎么判断哪条是新的:后缀对齐在翻历史和撤回时整屏重报
python·算法
甜到心里的蛋糕2 小时前
从 QQ 机器人到 B 站 AI 运营:一套可复现的视频流水线踩坑实录
运维·人工智能·python·自动化·视频制作