Python7.18元组

it2022-05-05  155

元组

有序可重复不可更改

符号使用()

定义:x =(a,b,c)

元组的创建

空元组创建

单元素元组创建,需要在单元素后面加逗号

tp1 = ("abc") tp2 = ("abc",) print(type(tp1)) print(type(tp2)) <class 'str'> <class 'tuple'>

多元素元组的创建,包含多种数据类型

拼接

tp1 = ("abc",) tp2 = ("abc",) print(tp2+tp1) ('abc', 'abc')

重复

tp2 = ("abc",) print(tp2*3) ('abc', 'abc', 'abc')

索引(偏移) 切片

tp2 = ("abc", "sdf", "sad") print(tp2[1]) print(tp2[:2]) sdf ('abc', 'sdf')

元组内部的列表可以改变

tp2 = ("abc", "sdf", "sad", ["aa", "bb", "cc", "dd"]) tp2[3][0]="123" print(tp2) ('abc', 'sdf', 'sad', ['123', 'bb', 'cc', 'dd'])

索引查

切片查

index()

tp2 = ("abc", "sdf", "sad", ["aa", "bb", "cc", "dd"]) tp2[3][0]="123" print(tp2) print(tp2.index("sad")) ('abc', 'sdf', 'sad', ['123', 'bb', 'cc', 'dd']) 2

增 不能

删 删除某个元素,不能;但可以全删了

tp2 = ("abc", "sdf", "sad", ["aa", "bb", "cc", "dd"]) print(tp2) del tp2 print(tp2) ('abc', 'sdf', 'sad', ['aa', 'bb', 'cc', 'dd']) Traceback (most recent call last): File "/Users/shaojun/PycharmProjects/7.18/8.py", line 5, in <module> print(tp2) NameError: name 'tp2' is not defined

最大值,最小值

tp = ("a", "b", "c") print("a" in tp) print(max(tp)) print(min(tp)) True c a

遍历

元素遍历

tp = ("a", "b", "c") for i in tp: print(i) a b c

索引遍历

tp = ("a", "b", "c") for i in range(len(tp)): print(tp[i]) a b c

枚举enumerate

tp = ("a", "b", "c") for i in enumerate(tp): print(i) (0, 'a') (1, 'b') (2, 'c')ed

最新回复(0)