【第三章】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])
相关推荐
重生之后端学习5 分钟前
苍穹外卖-day03
java·开发语言·数据库·spring boot·mysql·spring·tomcat
好想打kuo碎26 分钟前
轻量安全的密码管理工具Vaultwarden
linux·安全·ubuntu
Mayer_WOT27 分钟前
Jetson Orin AGX Getting Start with Pytorch
linux
咖啡配辣条29 分钟前
Python基础09
python
超大力王30 分钟前
DAY 45 超大力王爱学Python
开发语言·python
林-梦璃31 分钟前
Python开发基础手语识别(基础框架版)
开发语言·python·手语识别
追风赶月、1 小时前
【QT】信号和槽
开发语言·qt
wodownload21 小时前
CS003-2-2-perfermance
java·开发语言·jvm
RockyRich1 小时前
突然无法调用scikit-learn、xgboost
python·机器学习·scikit-learn
真的很上进1 小时前
2025最全TS手写题之partial/Omit/Pick/Exclude/Readonly/Required
java·前端·vue.js·python·算法·react·html5