元组

it2022-05-05  106

文章目录

元组特点:元组的创建:查增,不能删,del 直接删除元组的常用操作最大最小值遍历

元组

特点:

有序可重复不可更改

元组的创建:

te = (1,2,3) te = () # 空元组的创建,不能添加元素 te = (1,) # 单元素的元组创建需加上一个逗号,否则括号将视为运算符号 sr = str() # 通过函数创建字符串 tp = tuple() # 通过函数创建元组 # 多元素元组的创建,包含多种数据类型

(1)拼接

tp = (1, 2, 3) tp2 = (4, 5) print(tp + tp2) (1, 2, 3, 4, 5)

(2)重复

tp = (1, 2, 3) print(tp * 3) (1, 2, 3, 1, 2, 3, 1, 2, 3)

(3)索引(偏移) 切片

tp = (1, 2, 3, 4, '5') print(tp[1]) print(tp[2:5]) 2 (3, 4, '5') tp = (1, 2, 3, "a", "b",["aa", "bb", "cc", "dd"]) print(tp[2]) tp[2] = 33 File "D:/python/test1/day03.py", line 302, in <module> tp[2] = 33 TypeError: 'tuple' object does not support item assignment tp[5][2] = 'cccc' # 元组保存的是对列表的引用,当列表被修改时,由于地址未更改,所以元组也随着更改 print(tp) (1, 2, 3, 'a', 'b', ['aa', 'bb', 'cccc', 'dd'])

索引查切片查.index() tp = (1, 2, 3, "a", "b", ["aa", "bb", "cc", "dd"]) print(tp.index("a")) # 返回第一次索引值出现的位置,只能查看第一层,找不到"aa" 3

增,不能

删,del 直接删除

tp = (1, 2, 3, "a", "b", ["aa", "bb", "cc", "dd"]) print(id(tp)) # 2612747065480 del tp # 仅删除变量名,对象在被回收前依然存在,再次用一个变量名指向该对象,地址不变 tp = (1, 2, 3, "a", "b", ["aa", "bb", "cc", "dd"]) print(id(tp)) # 2612747065480

元组的常用操作

最大最小值

tp = (1, 2, 3) print(max(tp), min(tp)) 3 1

遍历

tp = (1, 2, 3, "a", "b", ["aa", "bb", "cc", "dd"]) # 元素遍历 for i in tp: print(i, end=' ') print() # 索引遍历 for i in range(len(tp)): print(tp[i], end=' ') print() # 枚举enumerate for index, value in enumerate(tp): print((index, value), end=' ') 1 2 3 a b ['aa', 'bb', 'cc', 'dd'] 1 2 3 a b ['aa', 'bb', 'cc', 'dd'] (0, 1) (1, 2) (2, 3) (3, 'a') (4, 'b') (5, ['aa', 'bb', 'cc', 'dd']) tp = ((1, 2, 3), (4, 5, 6), (7, 8, 9)) print(tp[1][1]) 5 tp = (((1, 2, 3), (4, 5, 6), (7, 8, 9)), ((11, 22, 33), 5, 6), (7, 8, 9)) print(tp[0][1][1]) 5

最新回复(0)