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)

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

相关推荐
南京云森杉木桩5 分钟前
水利木桩源头直供,质量可靠价格更优
大数据·python
Aaron - Wistron14 分钟前
Python基础教程2/4(复合数据结构)
python
小柯南敲键盘17 分钟前
跨境电商图片翻译与视频字幕翻译工具推荐
python·音视频
ZC跨境爬虫40 分钟前
LeetCode 13. 罗马数字转整数(多解法详解 + Java Python 实现)
java·python·leetcode
machnerrn1 小时前
智慧交通系列(一)-十字路口车辆闯红灯检测告警抓拍系统(附含数据+源码+模型)
人工智能·python·深度学习
现代野蛮人1 小时前
【深度学习实验】—— 利用 RNN 模型进行心脏病预测
pytorch·python·tensorflow·ml
LayZhangStrive1 小时前
融360 一面
java·面试·后端开发
2601_956319881 小时前
2026年用示例、拆解和练习提升量化理解效率
人工智能·python
王志来137944730082 小时前
从分散到集成:工控服务器机箱采购如何实现“一站式”破局
运维·服务器·人工智能·python
三十岁老牛再出发2 小时前
08.18每日总结
c++·python·numpy·pandas