Python—元组tuple的基础知识

it2022-05-05  146

文章目录

元组特点:创建(1)拼接(2)重复(3)索引(偏移) 切片(4)增删改查查增删改 遍历

元组

特点:

有序可以重复不可更改(元组中的列表可以更改,更改后元组发生变化)

符号使用()

整体用(),元素用,隔开

创建

空元组的创建,不能添加元素单元素元组的创建,需要在单元素后面加个, tp=() tp=('aaa',) 多元素元组的创建,包含多种数据类型

(1)拼接

li1=("1",) li2=("x",) print(li1+li2)

(2)重复

print(li1*3)

(3)索引(偏移) 切片

tp=('c',[1,2],'taaa',1) print((tp[0],tp[3])) print(tp[:3]) print(tp[::-1]) print(tp[2][0]) ('c', 1) ('c', [1, 2], 'taaa') (1, 'taaa', [1, 2], 'c') t

(4)增删改查

索引切片index()返回第一个要查找元素的位置

不可

不可删除一个元素

可用del删除整个元组

只能改元组中列表中的元素

遍历

元素遍历 tp=('c','i','t','y','1','9','0','9') for i in tp: print(i) 索引遍历 tp=('c','i','t','y','1','9','0','9') for i in range(len(tp)): print(tp[i]) 枚举enumerate tp=('c','i','t','y','1','9','0',[1,2,3]) for i in enumerate(tp): print(i,end=' ') # (0, 'c') (1, 'i') (2, 't') (3, 'y') (4, '1') (5, '9') (6, '0') (7, [1, 2, 3])

元组中大部分用法与list列表类似,要多注意增删改查的用法


最新回复(0)