python---元组(Tuple)

文章目录

元组是Python中的一种内置数据类型,它是一个不可变(immutable)、有序的序列。元组用圆括号()表示,元素之间用逗号分隔。

基本特性

1、不可变性:一旦创建,元组的内容不能修改(不能添加、删除或更改元素)

2、有序性:元素按照插入顺序存储,可以通过索引访问

3、可包含任意类型:可以包含数字、字符串、列表、甚至其他元组等

4、允许重复元素

创建元组

创建元组时,如果只有一个元素,后面不加逗号,则不是元组类型。例如not_a_tuple = (5)为整数型,not_a_tuple = ('c')为字符串型

bash 复制代码
# 空元组
empty_tuple = ()
print(f"empty_tuple is {empty_tuple}")

# 包含元素的元组
numbers = (1, 2, 3, 4)
fruits = ('apple', 'banana', 'cherry')
print(f"numbers is {numbers}")
print(f"fruits is {fruits}")

# 只有一个元素的元组(注意末尾的逗号)
single_element = (5,)  # 这是一个元组
print(f"single_element is {single_element}", "type of single_element is", type(single_element))
not_a_tuple = (5)      # 这不是元组,只是一个整数
print(f"not_a_tuple is {not_a_tuple}", "type of not_a_tuple is", type(not_a_tuple))

# 不使用括号创建(元组打包)
colors = 'red', 'green', 'blue'
print(f"colors is {colors}")

访问元组元素

bash 复制代码
t = ('a', 'b', 'c', 'd', 'e')

# 通过索引访问
print(t[0])   # 'a'
print(t[2])   # 'c'

# 负索引
print(t[-1])  # 'e'(最后一个元素)

# 切片
print(t[1:3]) # ('b', 'c')

元组操作

bash 复制代码
# 连接元组
tuple1 = (1, 2, 3)
tuple2 = ('a', 'b')
combined = tuple1 + tuple2  # (1, 2, 3, 'a', 'b')

# 重复元组
repeated = tuple1 * 2  # (1, 2, 3, 1, 2, 3)

# 成员检查
print(2 in tuple1)  # True
print('x' in tuple1) # False

# 长度
print(len(tuple1))  # 3

元组解包(Unpacking)

基本解包

point = (10, 20)

x, y = point

print(x) # 10

print(y) # 20

使用*收集剩余元素

bash 复制代码
numbers = (1, 2, 3, 4, 5)
first, *middle, last = numbers
print(first)   # 1
print(middle)  # [2, 3, 4](注意变成了列表)
print(last)    # 5

# 交换变量 不适用括号创建元组
a, b = 1, 2
a, b = b, a    # 交换a和b的值
print(f"a = {a}, b = {b}")

元组方法

由于元组不可变,它只有两个方法:

1、count() - 返回指定值出现的次数

2、index() - 返回指定值的第一个索引

注意:元组没有增删改查的方法。

bash 复制代码
t = (1, 2, 3, 2, 4, 2)

print(t.count(2))  # 3
print(t.index(3))  # 2

元组与列表的比较

特性 元组 (Tuple) 列表 (List)
可变性 不可变 可变
语法 使用() 使用[]
性能 更快 较慢
内存使用 更少 较多
安全性 更安全 较不安全

使用场景

1、当需要确保数据不被修改时(如常量集合)

2、作为字典的键(因为元组不可变,而列表不能作为键)

3、函数返回多个值时(实际上返回的是一个元组)

4、性能敏感的场景(元组比列表更高效)

c 复制代码
# 函数返回多个值(实际上是返回一个元组)
def get_stats(numbers):
    return min(numbers), max(numbers), sum(numbers)/len(numbers)

# 字典中使用元组作为键
locations = {
    (35.6895, 139.6917): "Tokyo",
    (40.7128, -74.0060): "New York"
}

元组嵌套

bash 复制代码
t = (1, (2, 3), (4, (5, 6)))
print(t[1])        # 输出: (2, 3)
print(t[1][0])     # 输出: 2
print(t[2][1][0])  # 输出: 5
相关推荐
土了个豆子的20 分钟前
02.继承MonoBehaviour的单例模式基类
开发语言·visualstudio·单例模式·c#·里氏替换原则
qq_1728055926 分钟前
Go 自建库的使用教程与测试
开发语言·后端·golang
久绊A32 分钟前
Hydra-SSH 破解安全防范
开发语言·php
ZZHow102433 分钟前
02OpenCV基本操作
python·opencv·计算机视觉
阿昭L39 分钟前
c++中获取随机数
开发语言·c++
计算机学长felix1 小时前
基于Django的“酒店推荐系统”设计与开发(源码+数据库+文档+PPT)
数据库·python·mysql·django·vue
3壹1 小时前
数据结构精讲:栈与队列实战指南
c语言·开发语言·数据结构·c++·算法
站大爷IP1 小时前
Python随机数函数全解析:5个核心工具的实战指南
python
悟乙己1 小时前
使用 Python 中的强化学习最大化简单 RAG 性能
开发语言·python·agent·rag·n8n
max5006001 小时前
图像处理:实现多图点重叠效果
开发语言·图像处理·人工智能·python·深度学习·音视频