【第三章】Python基础之元组tuple

元组tuple

1、一个有序的元素组成的集合

2、使用小括号 ( ) 表示

3、元组是不可变对象

初始化

tuple() -> empty tuple

tuple(iterable) -> tuple initialized from iterable's items

复制代码
t1 = () # 空元组
t2 = (1,) # 必须有这个逗号
t3 = (1,) * 5     输出:(1, 1, 1, 1, 1)
t3 = (1) * 5   	 	输出:5
t4 = (1, 2, 3)
t5 = 1, 'a'
t6 = (1, 2, 3, 1, 2, 3)
t7 = tuple() # 空元组
t8 = tuple(range(5))
t9 = tuple([1,2,3])

索引

索引和列表规则一样,不可以超界

复制代码
输入:x = (1,2,3,4,'abc',range(5),[],(),None)
	 x
输出:(1, 2, 3, 4, 'abc', range(0, 5), [], (), None)


输入:x[0],x[-1]
输出:(1, None)



输入:x[0] = 100				#TypeError: 'tuple'对象不支持项赋值
输出:TypeError: 'tuple' object does not support item assignment 

查询

方法和列表一样,时间复杂度也一样。index、count、len等

复制代码
输入:x.index(2)
输出:1

输入:x.index(0)				#ValueError: tuple.index(x): x不在元组中
输出:ValueError: tuple.index(x): x not in tuple 

x.count(1)
1

len(x)
9

增删改

元组元素的个数在初始化的时候已经定义好了,所以不能为元组增加元素、也不能从中删除元素、也不 能修改元素的内容。

但是要注意下面这个例子

复制代码
输入:(1,)+(1,)
输出:(1, 1)


输入:(1,3) * 3
输出:(1, 3, 1, 3, 1, 3)

输入:((1,),) * 3
输出:((1,), (1,), (1,))

输入:a = ([3],) * 3
	 a[0][0] = 500
	 a

输出:([500], [500], [500])
相关推荐
深紫色的三北六号2 小时前
Linux 服务器磁盘扩容与目录迁移:rsync + bind mount 实现服务无感迁移(无需修改配置)
linux·扩容·服务迁移
花酒锄作田6 小时前
使用 pkgutil 实现动态插件系统
python
SudosuBash6 小时前
[CS:APP 3e] 关于对 第 12 章 读/写者的一点思考和题解 (作业 12.19,12.20,12.21)
linux·并发·操作系统(os)
前端付豪10 小时前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽10 小时前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战11 小时前
Pydantic配置管理最佳实践(一)
python
哈基咪怎么可能是AI16 小时前
为什么我就想要「线性历史 + Signed Commits」GitHub 却把我当猴耍 🤬🎙️
linux·github
阿尔的代码屋16 小时前
[大模型实战 07] 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent
人工智能·python
十日十行1 天前
Linux和window共享文件夹
linux
AI探索者1 天前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python