元组

it2022-05-06  3

文章目录

元组1.特点2.定义3.创建4.拼接5.重复6.索引(偏移)7.切片8.查8.1索引查8.2切片查 9 删除10.最大值与最小值11.遍历

元组

1.特点

有序

可重复

好处值不会改变可以减少很多报错。

不可改变

若元组里面有列表,则可以修改元组中的列表 tp=(1,2,3,4,5,6,7,8,['abc','def','qwe']) print(id(tp)) tp[-1][1]='ok' print(tp) print(id(tp)) #输出 91638320 (1, 2, 3, 4, 5, 6, 7, 8, ['abc', 'ok', 'qwe']) 91638320

2.定义

元组使用小括号,列表使用方括号。元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可。

3.创建

空元组的创建 tp=() tp1=tuple() print(type(tp)) print(type(tp1)) #输出 <class 'tuple'> <class 'tuple'> 单元素元组的创建 str1=('abc') tp=('abc',) print(type(str1)) print(type(tp)) #输出 <class 'str'> <class 'tuple'>

4.拼接

tp=(1,2,3,4) tp1=(5,6,7,8) print(tp+tp1) #输出 (1, 2, 3, 4, 5, 6, 7, 8)

5.重复

tp=(1,2,3,4) print(tp*3) #输出 (1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4)

6.索引(偏移)

tp=(1,2,3,4) print(tp[2]) print(tp[-1]) #输出 3 4

7.切片

tp=(1,2,3,4,5,6,7,8) print(tp[1:5:2]) print(tp[-4:-1:1]) print(tp[0:]) print(tp[::-1]) #输出 (2, 4) (5, 6, 7) (1, 2, 3, 4, 5, 6, 7, 8) (8, 7, 6, 5, 4, 3, 2, 1)

8.查

8.1索引查

index() tp = ('a','b','c','d','e','f') print(tp.index('d')) #输出 3

8.2切片查

tp=(1,2,3,4,5,6,7,8) print(tp[1:5:2]) print(tp[-4:-1:1]) print(tp[0:]) print(tp[::-1]) #输出 (2, 4) (5, 6, 7) (1, 2, 3, 4, 5, 6, 7, 8) (8, 7, 6, 5, 4, 3, 2, 1)

9 删除

删除某个元素,不能删除全部元素,包括元组本身。 del相当于把变量放到垃圾站中,短时间内赋同样的值,id是不会发生改变的。长时间后会释放内存。 tp = ('a','b','c','d','e','f') del tp print(tp) #输出 会报错,tp未定义

10.最大值与最小值

tp = ('a','b','c','d','e','f') print(max(tp),min(tp)) #输出 f a

11.遍历

元素遍历

索引遍历

枚举遍历

tp = ('a', 'b', 'c', 'd', 'e', 'f') for i in tp: print(i, end=' ') print('') for i in range(len(tp)): print(tp[i], end=' ') #python中()括号一般都表示函数,切片使用的都是[]括号,所以即使元组使用() #定义,切片时依然使用[]。 print('') for i in enumerate(tp,1): print(i) #输出 a b c d e f a b c d e f (1, 'a') (2, 'b') (3, 'c') (4, 'd') (5, 'e') (6, 'f')

最新回复(0)