元组
- 有序
- 可重复的
- 不可改变的
符号使用()
元组的创建
-
单元素元组的创建,需要在单元素后面添加一个逗号
-
tp=("abc") print(type(tp)) tp=("abc",) print(type(tp)) # <class 'str'> <class 'tuple'>
-
多元素元组的创建,包含多种数据类型
(1)拼接
(2)重复
(3)索引(偏移) 切片
tp=("1","2","3")
tp2=("a","b","c")
print(tp+tp2)
print(tp*3)
print(tp[:2])
print(tp[:-1])
print(tp[0:3])
#
('1', '2', '3', 'a', 'b', 'c')
('1', '2', '3', '1', '2', '3', '1', '2', '3')
('1', '2')
('1', '2')
('1', '2', '3')
查
-
索引查
-
切片查
-
index()
-
tp=(1,2,3,"a","b",["aa","bb","cc","dd"]) print(tp.index("a")) # 3
增,不能
删,删除某个元素,不能;但可以全部删了
tp=(1,2,3,"a","b",["aa","bb","cc","dd"])
print(tp.index("a"))
del tp
print(tp)
报错,显示没有定义tp
最大值,最小值
max(tp)
min(tp)
遍历
元素遍历
索引遍历
枚举enumerate
tp=("a","b","c")
for i in tp:
print(i)
for i in range(len(tp)):
print(tp[i])
for i in enumerate(tp,2):
print(i)
#
a
b
c
a
b
c
(2, 'a')
(3, 'b')
(4, 'c')