python中的tuple

扫码查看

tuple 元组可看做特殊的列表,元组中的一级元素不可变。元组元素不可删除/追加/更改

1.元组的定义

# 定义一个空的元组并给他赋值 为了区分元组和方法都使用的小括号可以在元组最后一个元素之后添加一个逗号 
tu = ("hello", "world", 1, ("hi", "nice"), ["楚国", "燕国"],"age", )

2.元组元素的获取

# 元组元素的获取 索引获取
tu = ("hello", "world", 1, ("hi", "nice"), ["楚国", "燕国"],"age",) 
v1
= tu[0]
v2
= tu[3][0]

# 切片获取 切片回去的结果是元组
v3 = tu[0:2]

3.元组元素的遍历

# for 遍历 元组元素
tu = ["hello", "world", 1, ("hi", "nice"), ["楚国", "燕国"],"age",]
for item in tu:
    print(item)

4.元组中的方法

# 元组中方法只有两个 index() 和count()
# 获取某个元素的索引
tu = ["hello", "world", 1, ("hi", "nice"), ["楚国", "燕国"],"age","hello"]
idx = tu.index("hello")
# 获取某个元素出现的次数
ct = tu.count("hello")

5.元组中的列表元素可变

# 元组一级元素不可变 但它的元素如果是可变的列表,那列表中的元素可变
tu = ["hello", "world", 1, ("hi", "nice"), ["楚国", "燕国"],"age",]
tu[4][0] = "秦国"
12-17 03:46
查看更多