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
相关推荐
其美杰布-富贵-李15 分钟前
tsai 完整训练流程实践指南
python·深度学习·时序学习·fastai
m0_4626052225 分钟前
第N9周:seq2seq翻译实战-Pytorch复现-小白版
人工智能·pytorch·python
纪伊路上盛名在25 分钟前
记1次BioPython Entrez模块Elink的debug
前端·数据库·python·debug·工具开发
CryptoRzz26 分钟前
日本股票 API 对接实战指南(实时行情与 IPO 专题)
java·开发语言·python·区块链·maven
ss27327 分钟前
考研加油上岸祝福弹窗程序
python
yugi98783827 分钟前
基于M序列的直扩信号扩频码生成方法及周期长码直扩信号的MATLAB实现方案
开发语言·matlab
乾元34 分钟前
基于时序数据的异常预测——短期容量与拥塞的提前感知
运维·开发语言·网络·人工智能·python·自动化·运维开发
江上清风山间明月35 分钟前
使用python将markdown文件生成pdf文件
开发语言·python·pdf
凯_kyle35 分钟前
Python 算法竞赛 —— 基础篇(更新ing)
笔记·python·算法
j_xxx404_38 分钟前
C++算法入门:二分查找合集(二分查找|在排序数组中查找元素的第一个和最后一个位置)
开发语言·c++