Python元组基础
元组是不可变序列,元素一旦创建不可修改,适合存储固定数据。
元组创建
基本创建
Python
# 圆括号创建
t1 = (1, 2, 3)
t2 = ("a", "b", "c")
# 混合类型
t3 = (1, "hello", True, 3.14)
# 单元素元组(必须加逗号)
t4 = (1,) # 单元素元组
t5 = (1) # 不是元组,是整数
# 空元组
t6 = ()
t7 = tuple()
无括号创建
Python
# 逗号分隔自动创建元组
t = 1, 2, 3
print(type(t)) # tuple
print(t) # (1, 2, 3)
tuple() 函数创建
Python
# 从列表创建
t1 = tuple([1, 2, 3])
print(t1) # (1, 2, 3)
# 从字符串创建
t2 = tuple("hello")
print(t2) # ('h', 'e', 'l', 'l', 'o')
# 从 range 创建
t3 = tuple(range(5))
print(t3) # (0, 1, 2, 3, 4)
不可变性
元素不可修改
Python
t = (1, 2, 3)
# t[0] = 10 # TypeError: 元组不支持修改
# 元组没有 append、insert、remove 等方法
不可添加删除
Python
t = (1, 2, 3)
# t.append(4) # AttributeError
# del t[0] # TypeError
内容可变的元素不受限制
Python
# 元组内包含列表
t = (1, [2, 3], 4)
t[1].append(5) # 可以修改元组内的列表
print(t) # (1, [2, 3, 5], 4)
元组的不可变是指元组本身,不限制其元素的内部状态。
索引与切片
索引访问
Python
t = (1, 2, 3, 4, 5)
print(t[0]) # 1
print(t[-1]) # 5
print(t[2]) # 3
切片操作
Python
t = (1, 2, 3, 4, 5)
print(t[1:4]) # (2, 3, 4)
print(t[:3]) # (1, 2, 3)
print(t[::-1]) # (5, 4, 3, 2, 1)
切片返回新元组,不影响原元组。
元组操作
查询方法
Python
t = (1, 2, 3, 2)
# 统计次数
print(t.count(2)) # 2
# 查找位置
print(t.index(2)) # 1(第一个位置)
# 检查存在
print(2 in t) # True
常用函数
Python
t = (1, 2, 3, 4, 5)
print(len(t)) # 5
print(min(t)) # 1
print(max(t)) # 5
print(sum(t)) # 15
拼接与重复
Python
t1 = (1, 2)
t2 = (3, 4)
# 拼接(创建新元组)
print(t1 + t2) # (1, 2, 3, 4)
# 重复
print(t1 * 3) # (1, 2, 1, 2, 1, 2)
解包赋值
基本解包
Python
t = (1, 2, 3)
a, b, c = t
print(a, b, c) # 1 2 3
扩展解包
Python
t = (1, 2, 3, 4, 5)
first, *rest = t
print(first) # 1
print(rest) # [2, 3, 4, 5]
first, *middle, last = t
print(first, middle, last) # 1 [2, 3, 4] 5
多返回值
Python
def get_info():
return ("Alice", 25, "Beijing")
name, age, city = get_info()
print(name, age, city) # Alice 25 Beijing
元组 vs 列表
对比表
| 特性 | 元组 | 列表 |
|---|---|---|
| 可变性 | 不可变 | 可变 |
| 创建语法 | () 或逗号 | [] |
| 方法数量 | 少(count, index) | 多(append, remove 等) |
| 性能 | 更快(创建、遍历) | 较慢 |
| 内存占用 | 更小 | 较大 |
| 作为字典键 | 可以 | 不可以 |
| 哈希支持 | 支持 | 不支持 |
使用场景
Python
# 元组:固定数据、配置、坐标、返回值
coordinates = (10, 20)
config = ("localhost", 3306, "admin")
# 列表:动态数据、需要增删改
shopping_list = ["apple", "banana"]
shopping_list.append("orange")
元组作为字典键
元组可做字典键
Python
# 元组作为键
locations = {
(10, 20): "Point A",
(30, 40): "Point B"
}
print(locations[(10, 20)]) # Point A
# 列表不能作为键
# {[1, 2]: "value"} # TypeError
嵌套元组
多维元组
Python
matrix = (
(1, 2, 3),
(4, 5, 6),
(7, 8, 9)
)
print(matrix[0]) # (1, 2, 3)
print(matrix[0][1]) # 2
要点总结
- 元组不可变,创建后元素不可修改
- 单元素元组必须加逗号
(1,) - 元组可做字典键,列表不可以
- 元组方法少:count、index
- 适合存储固定数据、多返回值、字典键
📝 发现内容有误?点击此处直接编辑