【第三章】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])
相关推荐
helloweilei9 小时前
python 抽象基类
python
用户83562907805110 小时前
Python 实现 PPT 转 HTML
后端·python
Johny_Zhao10 小时前
centos7安装部署openclaw
linux·人工智能·信息安全·云计算·yum源·系统运维·openclaw
haibindev11 小时前
在 Windows+WSL2 上部署 OpenClaw AI员工的实践与踩坑
linux·wsl2·openclaw
zone773915 小时前
004:RAG 入门-LangChain读取PDF
后端·python·面试
zone773915 小时前
005:RAG 入门-LangChain读取表格数据
后端·python·agent
树獭非懒1 天前
AI大模型小白手册|Embedding 与向量数据库
后端·python·llm
唐叔在学习1 天前
就算没有服务器,我照样能够同步数据
后端·python·程序员
曲幽1 天前
FastAPI流式输出实战与避坑指南:让AI像人一样“边想边说”
python·ai·fastapi·web·stream·chat·async·generator·ollama