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)

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

相关推荐
满怀冰雪3 小时前
25-迁移学习入门:加载预训练模型并微调
人工智能·python·机器学习·迁移学习·paddle
2601_962284503 小时前
安卓APP UI自动化测试:Python + UiAutomator2 + pytest + pytest-html
python·pytest·uiautomator2·ui自动化测试·安卓app
2601_962078033 小时前
构建RESTful APIs:使用Python和Flask
python·flask·web开发·api设计·构建restfulapis
半亩码田3 小时前
C#转Python第4.5篇:单元测试:pytest vs xUnit/NUnit
python·单元测试·c#
2601_962300813 小时前
Python + Requests + Pytest + Excel + Allure:接口自动化测试项目实战
python·excel·pytest·allure·requests
Zane19943 小时前
两个线程算两遍循环,为什么只快了一点点不是两倍?GIL连环追问
后端·python
重生之小比特3 小时前
【Java SE】程序逻辑控制
java·开发语言·python
小灰灰搞电子3 小时前
Python 函数参数分隔符 *:Keyword-Only Arguments 原理与实践
开发语言·python
2601_962297253 小时前
Authlib 0.13通用Python认证授权库wheel安装包(支持Python 2/3)
python·jwt·oauth2.0·authlib·openidconnect
SamChan903 小时前
大文件多语言PDF翻译性能实测:300页文档的耗时、内存占用与失败率分析
python·ai·pdf·机器翻译