介绍

Tuple —— 元组,有序的、不可变的元素的集合,和列表比较相似,但拥有一些特性。

  • 不可变, 一旦元组被创建,其元素就不能被改变。这种不可变性提供了数据的完整性,可以确保了整个代码执行的一致性。
  • 高性能,元组比列表消耗的内存更少,执行速度更快,适用于对性能要求很高的情况。
  • 可哈希,元素是hashable的,可以作为字典的键使用,方便更灵活地组织数据,比如pandas中DataFrame的组合索引就是用的元组。

优势

提升代码性能

元组具有更高的内存效率和更快的执行时间,它是处理恒定数据时的最佳选择。在处理大数据集和对性能敏感的程序时尤为重要

保持数据完整

元组的不可变性可以防止数据被意外修改,确保数据在程序执行过程中保持一致。

多用途和可读性

元组可以用来存储函数的多个返回值,或者作为字典的键。

1
2
3
4
5
6
def get_name_and_age():
return ("Alice", 30)

# 拆包赋值,可迭代对象都可以进行拆包
name, age = get_name_and_age()
print("Name:", name, "Age:", age)

元组可以明确指出数据是常量,不可修改,提高代码可读性。

元组的创建和访问

创建元组,用小括号()或者tuple()对象。

1
2
3
4
5
6
7
8
9
# Creating a tuple with integers, strings, and a nested tuple
mixed_tuple = (1, "apple", (2, "banana"))

print(mixed_tuple) # Output: (1, 'apple', (2, 'banana'))

# Using the tuple() constructor to create a tuple
fruits = tuple(["apple", "banana", "cherry"])

print(fruits) # Output: ('apple', 'banana', 'cherry')

访问元组的元素。

1
2
3
4
5
6
7
8
9
10
11
12
# Creating a tuple of numbers
numbers = (1, 2, 3, 4, 5)

first_number = numbers[0]
print("First number:", first_number) # Output: First color: red

# Accessing elements from index 1 (inclusive) to index 4 (exclusive)
sliced_numbers = numbers[1:4]

print(sliced_numbers) # Output: (2, 3, 4)


一些进阶技巧

具名元组

collections模块中的具名元组是元组的扩展,它提供了命名的字段,使你的代码更容易阅读和自我解释。

1
2
3
4
5
6
7
8
9
10
11
from collections import namedtuple

# Creating a named tuple class
Person = namedtuple("Person", ["name", "age", "city"])

# Instantiating a named tuple object
person1 = Person("Alice", 30, "New York")

# Accessing named tuple fields
print("Name:", person1.name, "Age:", person1.age, "City:", person1.city)
# Output: Name: Alice Age: 30 City: New York

用元组枚举

enumerate()函数返回一个产生元组的迭代器,每个元组包含一个索引和相应元素。

1
2
3
4
# Using enumerate() to loop through a list with tuple unpacking
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits, start=1):
print(f"{index}. {fruit}")

拆包

用下划线代替不需要的元素

1
2
3
4
# Use underscores for unwanted items
user_data = ("John", 44, "Male")
name, _, gender = user_data
print(f"Name: {name}; Gender: {gender}") #>>> Name: John; Gender: Male

*捕获所有的元素

1
2
3
4
5
6
# User * to capture all
numbers = (1, 2, 3, 4, 5)
first_num, *middle_nums, last_num = numbers
print("First Number:", first_num) # First Number: 1
print("Last Number:", last_num) # Last Number: 5
print("Remaining Numbers:", middle_nums) # Remaining Numbers: [2, 3, 4]

在元组前加*可以拆包获取元组所有元素

grouping_factors1 = ("country", "state")
grouping_factors2 = (*grouping_factors1, "city")
print("Factors 1:", grouping_factors1) # Factors 1: ('country', 'state')
print("Factors 2:", grouping_factors2) # Factors 2: ('country', 'state', 'city')

## 常见问题

- 单元素元组命名时需要加个逗号
- 拆包时元素数量不匹配
- 对不可变的元组进行修改