Skip to content

Python 元组

元组(tuple)是 Python 对象的一种有序、不可变(immutable)序列。‘不可变’ 意味着一旦创建了元组,其元素就不能被更改、添加或移除。元组类似于列表(list),但关键区别在于它们的不可变性。

元组通过将逗号分隔的值放在圆括号 () 内来定义。如果上下文清晰,圆括号是可选的,但使用它们是标准做法。

# Creating tuples
tuple1 = ('physics', 'chemistry', 1997, 2000)
tuple2 = (1, 2, 3, 4, 5)
tuple3 = "a", "b", "c", "d" # Parentheses optional here
empty_tuple = ()
# Tuple with a single element requires a trailing comma
single_element_tuple = (50,)
not_a_tuple = (50) # This is just the integer 50
print(type(single_element_tuple)) # Output: <class 'tuple'>
print(type(not_a_tuple)) # Output: <class 'int'>

与列表和字符串一样,元组元素使用从 0 开始的索引。您可以访问元素、对它们进行切片、连接元组以及重复它们。

使用方括号 [] 和索引来访问单个元素,或使用切片 [start:end:step] 来获取子元组。

tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5, 6, 7)
print(f"tup1[0]: {tup1[0]}") # Access first element
print(f"tup2[1:5]: {tup2[1:5]}") # Slice from index 1 up to (not including) 5
print(f"tup1[-1]: {tup1[-1]}") # Access last element

输出:

tup1[0]: physics
tup2[1:5]: (2, 3, 4, 5)
tup1[-1]: 2000

元组是不可变的。一旦创建,您不能更改元组中的元素。

tup1 = (12, 34.56)
# The following action is INVALID and will raise a TypeError:
# tup1[0] = 100
# TypeError: 'tuple' object does not support item assignment

但是,您可以通过组合现有元组或其部分来创建新元组。

tup1 = (12, 34.56)
tup2 = ('abc', 'xyz')
# Create a new tuple by concatenating tup1 and tup2
tup3 = tup1 + tup2
print(f"New tuple tup3: {tup3}")

输出:

New tuple tup3: (12, 34.56, 'abc', 'xyz')

如果元组包含可变对象(如列表),则可以更改该可变对象的内容,但该对象本身在元组中的位置保持不变。

tuple_with_list = (1, 2, ['a', 'b'])
print(f"Original: {tuple_with_list}")
# Modify the list inside the tuple (this is allowed)
tuple_with_list[2].append('c')
print(f"Modified: {tuple_with_list}")
# Attempting to replace the list object itself fails
# tuple_with_list[2] = ['x', 'y'] # TypeError!

由于元组是不可变的,您无法从元组中移除单个元素。

但是,您可以使用 del 语句删除整个元组对象。

tup = ('physics', 'chemistry', 1997, 2000)
print(f"Original tuple: {tup}")
# Delete the entire tuple object
del tup
# Attempting to access 'tup' now will raise a NameError
# print(tup)
# NameError: name 'tup' is not defined
print("Tuple 'tup' has been deleted.")

元组支持标准的序列操作,如连接 (+) 和重复 (*),它们会产生新的元组。

Python 表达式结果描述
len((1, 2, 3))3长度
(1, 2, 3) + (4, 5, 6)(1, 2, 3, 4, 5, 6)连接
('Hi!',) * 4('Hi!', 'Hi!', 'Hi!', 'Hi!')重复
3 in (1, 2, 3)True成员检查
for x in (1, 2, 3): print(x, end=' ')1 2 3 迭代

索引和切片的使用方式与列表和字符串完全相同。

T = ('spam', 'Spam', 'SPAM!', 'eggs')
Python 表达式结果描述
T[0]'spam'第一个元素(索引 0)
T[-1]'eggs'最后一个元素
T[1:3]('Spam', 'SPAM!')从索引 1 开始切片,直到(不包括)索引 3
T[::2]('spam', 'SPAM!')每隔一个元素

元组解包(Tuple Unpacking)是一个非常常见且强大的特性,您可以将元组的元素赋值给单独的变量。变量的数量必须与元组中元素的数量匹配。

point = (10, 20, 30)
x, y, z = point # Unpacking
print(f"x = {x}, y = {y}, z = {z}")
# Can be used for easy swapping
a = 5
b = 10
a, b = b, a # Swap values using tuple packing/unpacking
print(f"Swapped: a = {a}, b = {b}")
# Extended unpacking (Python 3)
numbers = (1, 2, 3, 4, 5)
first, second, *rest = numbers
print(f"first: {first}, second: {second}, rest: {rest}")
first, *middle, last = numbers
print(f"first: {first}, middle: {middle}, last: {last}")

输出:

x = 10, y = 20, z = 30
Swapped: a = 10, b = 5
first: 1, second: 2, rest: [3, 4, 5]
first: 1, middle: [2, 3, 4], last: 5

Python 包含可以操作元组的函数:

函数描述
len(tuple)返回元组中的总项目数。
max(tuple)返回元组中值最大的项目(项目必须可比较)。
min(tuple)返回元组中值最小的项目(项目必须可比较)。
sum(tuple)返回元组中所有项目的总和(项目必须是数字)。
tuple(iterable)将可迭代对象(如列表、字符串或 range)转换为元组。
sorted(tuple)返回一个新的列表,其中包含元组中所有项目按升序排列的结果。

注意:Python 2 中的 cmp(tuple1, tuple2) 函数已在 Python 3 中移除。请改用标准比较运算符(<、>、== 等),它们会按字典顺序比较元组。

尽管元组与列表相似,但在以下几种情况下元组非常有用: