元组
一、元组
- python内置的数据结构之一,是一个不可变序列
二、不可变序列与可变序列
不可变序列:字符串、元组
- 不可变序列:没有增、删、改的操作
可变序列:列表、字典
- 可变序列:可以对序列进行增、删改操作,对象地址不发生更改
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | '' ' 可变序列:列表、字典 '' ' lst=[10,20,45] print(id(lst)) lst.append(100) print(id(lst)) '' ' 不可变序列:字符串、元组 '' ' s= 'hello' print(id(s)) s=s+ 'world' print(id(s)) 运行结果: 2232750129536 2232750129536 2232750141168 2232750463280 |
三、元组的创建方式
1、直接小括号
2、使用内置函数tuple()
3、只包含一个元组的元素需要使用逗号和小括号
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | '' ' 第一种创建方式——使用() '' ' demo1=( 'hello' , 'world' ,98) print(demo1) print(type(demo1)) demo2= 'hello' , 'world' ,98 print(demo2) print(type(demo2)) demo3= 'hello' print(demo3) print(type(demo3)) #< class 'str' > #在这里,我们发现其是str类型,不再是元组类型,对于只有一个数据的元组,我们需要使用括号或者是逗号 demo4= 'hello' , print(demo4) print(type(demo4))#< class 'tuple' > '' ' 第二种方法——使用内置函数tuple() '' ' demo5=tuple(( 'python' , 'world' ,98)) print(demo5) print(type(demo5)) #空列表的创建方式 lst=[] lst1=list() #空字典的创建方式 d={} d2=dict() #空元组的创建方式 t=() t2=tuple() print(t) |
四、为什么要将元组设计成不可变序列
- 在多任务环境中,同时操作对象时不需要加锁
- 因此,在程序中尽量使用不可变序列
注意事项:
- 元组中存储的是对象的引用
- 如果元组中对象本身为不可变对象,则不能再引用其他对象
- 如果元组中对象是可变对象,则可变对象的引用不允许改变,但数据可以改变
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | demo=(10,[20,30],9) print(demo) print(demo[0],type(demo[0]),id(demo[0])) #< class 'int' > print(demo[1],type(demo[1]),id(demo[1])) #< class 'list' > print(demo[2],type(demo[2]),id(demo[2])) #< class 'int' > #demo[0]=100 报错:元组是并不允许修改元素的——TypeError: 'tuple' object does not support item assignment '' ' 由于列表是可变序列,所以可以改变列表,向列表中添加元素,而列表的内存地址不变 '' ' demo[1].append(100) #向列表中添加元素 print(demo[1],id(demo[1])) #可以发现其id号不变 运行结果: (10, [20, 30], 9) 10 < class 'int' > 1731897420368 [20, 30] < class 'list' > 1731902849344 9 < class 'int' > 1731897420336 [20, 30, 100] 1731902849344 |
五、元组的遍历
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | demo=( 'python' , 'world' ,98) '' ' 两种方法遍历元组 1、使用索引 2、使用 for 循环遍历 '' ' for i in demo: print(i) 运行结果: python world 98 |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)