Vanson's Eternal Blog

Python中的Tuple元组常见和高级用法

Python tuple.png
Published on
/7 mins read/---

创建元组

可以使用圆括号 () 或直接用逗号分隔元素来创建元组。

 
# 使用圆括号创建元组
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple)  # 输出: (1, 2, 3, 4, 5)
 
# 不使用圆括号创建元组
another_tuple = 1, 2, 3, 4, 5
print(another_tuple)  # 输出: (1, 2, 3, 4, 5)
 

访问元组元素

可以通过索引访问元组中的元素。

 
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple[0])  # 输出: 1
print(my_tuple[-1])  # 输出: 5
 

切片操作

可以使用切片操作获取元组的一个子集。

 
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple[1:3])  # 输出: (2, 3)
print(my_tuple[:3])   # 输出: (1, 2, 3)
print(my_tuple[3:])   # 输出: (4, 5)
print(my_tuple[::2])  # 输出: (1, 3, 5)
 

元组的不可变性

元组是不可变的,尝试修改元组中的元素会引发错误。

 
my_tuple = (1, 2, 3)
# my_tuple[0] = 10  # 会引发 TypeError: 'tuple' object does not support item assignment
 

元组的长度

可以使用 len() 函数获取元组的长度。

 
my_tuple = (1, 2, 3, 4, 5)
print(len(my_tuple))  # 输出: 5
 

元组的成员检查

可以使用 in 操作符检查元组中是否存在某个元素。

 
my_tuple = (1, 2, 3, 4, 5)
print(3 in my_tuple)  # 输出: True
print(6 in my_tuple)  # 输出: False
 

元组的比较

元组可以进行比较操作,比较时会逐个比较元组中的元素。

 
tuple1 = (1, 2, 3)
tuple2 = (1, 2, 4)
print(tuple1 < tuple2)  # 输出: True
print(tuple1 == tuple2)  # 输出: False
 

元组的连接和重复

可以使用 + 运算符连接两个元组,使用 * 运算符重复元组。

 
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
combined_tuple = tuple1 + tuple2
print(combined_tuple)  # 输出: (1, 2, 3, 4, 5, 6)
 
repeated_tuple = tuple1 * 3
print(repeated_tuple)  # 输出: (1, 2, 3, 1, 2, 3, 1, 2, 3)
 

元组的嵌套

元组可以嵌套,形成多维元组。

 
nested_tuple = ((1, 2), (3, 4), (5, 6))
print(nested_tuple[1])  # 输出: (3, 4)
print(nested_tuple[1][0])  # 输出: 3
 

元组的解包和 _ 忽略

在解包时,可以使用 _ 来忽略某些值。

 
my_tuple = (1, 2, 3, 4, 5)
a, _, c, _, _ = my_tuple
print(a, c)  # 输出: 1 3
 
coordinates = (3.14, 2.71)
x, y = coordinates  # x=3.14, y=2.71 ‌:ml-citation{ref="2" data="citationList"}
 
 
nested = (1, (2, 3))
a, (b, c) = nested  # a=1, b=2, c=3 ‌:ml-citation{ref="5" data="citationList"}
 
 

元组的 count() 和 index() 方法

count() 方法用于统计元组中某个元素的出现次数,index() 方法用于查找元组中某个元素的索引。

 
my_tuple = (1, 2, 2, 3, 4, 2)
print(my_tuple.count(2))  # 输出: 3
print(my_tuple.index(2))  # 输出: 1
 

元组的 zip() 和 enumerate()

zip() 可以将多个元组组合成一个元组列表,enumerate() 可以在遍历时获取元素的索引。

 
# 使用 zip() 组合多个元组
tuple1 = (1, 2, 3)
tuple2 = ('a', 'b', 'c')
zipped = list(zip(tuple1, tuple2))
print(zipped)  # 输出: [(1, 'a'), (2, 'b'), (3, 'c')]
 
# 使用 enumerate() 获取索引和值
for index, value in enumerate(tuple1):
    print(f"Index: {index}, Value: {value}")
# 输出:
# Index: 0, Value: 1
# Index: 1, Value: 2
# Index: 2, Value: 3
 

元组的 sorted()

可以使用 sorted() 对元组进行排序。

 
my_tuple = (3, 1, 4, 1, 5, 9, 2, 6, 5)
sorted_tuple = tuple(sorted(my_tuple))
print(sorted_tuple)  # 输出: (1, 1, 2, 3, 4, 5, 5, 6, 9)
 

元组的 map() 和 filter()

可以使用 map() 和 filter() 对元组进行批量操作。

 
# 使用 map() 对元组中的每个元素应用函数
my_tuple = (1, 2, 3, 4, 5)
squared = tuple(map(lambda x: x * x, my_tuple))
print(squared)  # 输出: (1, 4, 9, 16, 25)
 
# 使用 filter() 过滤元组中的元素
evens = tuple(filter(lambda x: x % 2 == 0, my_tuple))
print(evens)  # 输出: (2, 4)
 

元组的 reduce()

可以使用 reduce() 累积计算元组中的元素。

 
from functools import reduce
 
# 使用 reduce() 累积计算元组的和
my_tuple = (1, 2, 3, 4, 5)
sum_result = reduce(lambda x, y: x + y, my_tuple)
print(sum_result)  # 输出: 15
 

元组的解包和扩展

可以使用 * 运算符在解包时扩展元组。

 
my_tuple = (1, 2, 3, 4, 5)
a, *b, c = my_tuple
print(a)  # 输出: 1
print(b)  # 输出: [2, 3, 4]
print(c)  # 输出: 5
 

元组的 __add____mul__

可以使用 __add____mul__ 方法自定义元组的连接和重复操作。

 
class MyTuple(tuple):
    def __add__(self, other):
        return MyTuple(super().__add__(other))
 
    def __mul__(self, other):
        return MyTuple(super().__mul__(other))
 
my_tuple = MyTuple((1, 2, 3))
another_tuple = MyTuple((4, 5, 6))
combined_tuple = my_tuple + another_tuple
print(combined_tuple)  # 输出: (1, 2, 3, 4, 5, 6)
 
repeated_tuple = my_tuple * 3
print(repeated_tuple)  # 输出: (1, 2, 3, 1, 2, 3, 1, 2, 3)
 

元组的 __getitem____setitem__

虽然元组是不可变的,但可以通过继承 tuple 并重写 __getitem____setitem__ 方法来创建可变的元组类。

 
class MutableTuple(tuple):
    def __setitem__(self, key, value):
        lst = list(self)
        lst[key] = value
        self._replace(lst)
 
    def _replace(self, lst):
        self._internal = lst
 
    def __getitem__(self, key):
        return self._internal[key]
 
my_tuple = MutableTuple((1, 2, 3))
print(my_tuple[0])  # 输出: 1
my_tuple[0] = 10
print(my_tuple[0])  # 输出: 10
 

函数返回多个值

 
def get_stats(data):
    return min(data), max(data), sum(data)/len(data)
 
min_val, max_val, avg = get_stats((10, 20, 30))  # 拆包接收 ‌:ml-citation{ref="2" data="citationList"}
 
 

比列表性能好

元组比列表更轻量,适合存储不可变数据‌。

 
import sys
import timeit
 
list_mem = sys.getsizeof([1, 2, 3])  # 88 bytes(示例值)
tuple_mem = sys.getsizeof((1, 2, 3))  # 72 bytes(更小)‌:ml-citation{ref="3" data="citationList"}