【第三章】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])
相关推荐
mi20063 分钟前
银河麒麟v10 sp1更改data目录挂载
linux·运维
暴风鱼划水13 分钟前
卡码网语言基础课(Python) | 19.洗盘子
python·算法
Gitpchy26 分钟前
Day 23 机器学习管道 pipeline
python·机器学习
tan180°28 分钟前
Linux网络HTTP(下)(9)
linux·网络·http
程序员小远29 分钟前
使用Jmeter进行http接口测试
自动化测试·软件测试·python·测试工具·jmeter·http·接口测试
jf加菲猫38 分钟前
条款21:优先选用std::make_unique、std::make_shared,而非直接new
开发语言·c++
消失的旧时光-19431 小时前
Kotlin 高阶函数在回调设计中的最佳实践
android·开发语言·kotlin
半路_出家ren1 小时前
设计一个学生管理系统的数据库
linux·数据库·sql·mysql·网络安全·数据库管理员
着迷不白1 小时前
华为堡垒机
linux·运维·服务器·centos
飘忽不定的bug1 小时前
Atlas 200I AI加速模块-修改和打包文件系统
linux·ascend310b