Python3 元组

元组(tuple)与列表一样是有序的容器,但创建后不可修改:不能增删元素,也不能给元素重新赋值。这种不可变性让元组更安全、可哈希,适合表示"一组固定的值",也常作为字典的键。元组一般用圆括号 () 表示。

定义与括号

t1 = (1, 2, 3)
t2 = 1, 2, 3             # 省略括号也可以
print(t1)                # 输出:(1, 2, 3)
print(type(t2))          # 输出:<class 'tuple'>

单元素逗号陷阱

t = (5)
print(type(t))           # 输出:<class 'int'>(不是元组!)
t = (5,)
print(type(t))           # 输出:<class 'tuple'>

不可变性

元组内容不能修改,强行修改会抛 TypeError;若其中含列表等可变对象,该对象自身仍可改:

t = (1, 2, 3)
# t[0] = 99   # 报错:TypeError: 'tuple' object does not support item assignment

索引与切片

用法与列表一致,切片返回的仍是元组:

t = (10, 20, 30, 40)
print(t[0], t[-1])    # 输出:10 40
print(t[1:3])         # 输出:(20, 30)
print(len(t))         # 输出:4

元组解包

一次把多个值赋给多个变量,交换变量也只需一行:

point = (3, 4)
x, y = point          # 解包
print(x, y)           # 输出:3 4
a, b = 1, 2
a, b = b, a           # 交换变量
print(a, b)           # 输出:2 1

多个返回值

函数返回多个值时本质是返回元组,调用处解包接收:

def min_max(nums):
    return min(nums), max(nums)    # 返回元组

lo, hi = min_max([3, 1, 2])
print(lo, hi)         # 输出:1 3

作为字典键

元组不可变、可哈希,能作字典键;列表不行:

d = {(1, 2): "坐标"}
print(d[(1, 2)])      # 输出:坐标
# d[[1, 2]] = "x"     # 报错:TypeError: unhashable type: 'list'

namedtuple 与列表区别

collections.namedtuple 可创建带字段名的元组,用 . 访问成员:

from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(1, 2)
print(p.x, p.y)       # 输出:1 2
对比项元组 tuple列表 list
写法(1, 2)[1, 2]
是否可变不可变可变
可否作字典键可以不可以
常用场景固定的一组值需频繁增删改的数据

小结:元组是"只读列表",用不可变性换取安全与可哈希,解包、多返回值、字典键等场景都离不开它。

笔记加载中…