33、元组及其常见操作

小白量化 2025-12-09 16:17:43 45 举报

1、元组及其常见操作  tuple
1.1 含义
在Python中,元组是一种内置的数据结构,用于存储一系列的元素。但它与列表的主要区别在于元组是不可变的。
这意味着一旦你创建了一个元组,你就不能更改它的内容(即不能直接添加、删除或更改元组中的元素)。
元组通常用于存储那些不应该被改变的数据集合,比如一周的天数、一个点的坐标等。

1.2 格式

# 语法格式
变量 = (元素1, 元素2, 元素3, ...)
# 示例1
tua = (1, 2, 3, 4, 5, 6, 7)
print(tua, type(tua))
# 示例2:
tua = (1, 2, True, 'xiaobai', [1, 2, 3], (1, 2, 3))
print(tua, type(tua))

注意:当定义一个只包含一个元素的元组时,必须在元素末尾加上逗号(,),否则Python会将其视为该元素的数据类型本身,而不是一个元组

# 示例1
tua = (1)
print(tua, type(tua))
# 示例2
tua = (1,)
print(tua, type(tua))
# 示例3
tua = ("xiaobai")
print(tua, type(tua))
# 示例4
tua = ("xiaobai",)
print(tua, type(tua))

1.3 基本使用
(1)通过索引访问元组元素

# 示例
tua = ("aaa", 'bbb', 'ccc')
print(tua[0])
print(tua[1])
print(tua[2])
print(tua[3])    # IndexError: tuple index out of range
print(tua[-1])
print(tua[-2])
print(tua[-3])
print(tua[-4])   # IndexError: tuple index out of range

(2)元组切片

# 示例
tua = (11, 22, 33, 44, 55, 66, 77, 88, 99)
print(tua[-1:-11:-2])
# -1(99) -1-2(77) -1-2-2(55)  -1-2-2-2(33)  -1-2-2-2-2(11)
print(tua[-11:-1:2])  # -11 -> -1(99):从左往右  2:从左往右 方向一致,可以切取
# -11  -11+2(11) -11+2+2(33)  -11+2+2+2(55)  -11+2+2+2+2(77)

(3)元组是可迭代对象,支持for循环遍历

# 示例
tua = (11, 22, 33, 44, 55, 66, 77, 88, 99)
for i in tua:
   print(i*5)

1.4 元组常见操作
注意:与列表不同,元组一旦创建就不能被修改(即不能直接添加、删除或更改其元素),仅支持查询操作。

# 示例
tua = (1, 2, 3)
tua[0] = 8    # TypeError: 'tuple' object does not support item assignment

(1)in:检查一个元素是否存在于元组中。如果存在则返回True;否则返回False。
(2)not in:检查一个元素是否不存在于元组中。如果不存在则返回True;否则返回False

# 示例
name = ("xiaobai", "qinqin", "yaya", "ziyi")
print("xiaobai" in name)    # True
print("i" in name)           # False
print("hahha" not in name)   # True

(3)index(元素, 起始索引, 结束索引):查找元组中某个元素值第一次出现的索引(位置)。如果元素不存在于元组中,则抛出异常ValueError。

# 示例
fruits = ("apple", "banana", "cherry", "apple")
print(fruits.index("cherry"))   # 2
print(fruits.index("apple"))    # 0
print(fruits.index("pear"))   # ValueError: tuple.index(x): x not in tuple

# 使用 start 参数
print(fruits.index("apple", 1))  # 3

# 使用 start 和 stop 参数,遵循包前不包后规则
print(fruits.index("apple", 1, 3))   # ValueError: tuple.index(x): x not in tuple

(4)count(元素):统计某个元素在列表中出现的次数。

# 示例
fruits = ("apple", "banana", "cherry", "apple")
print(fruits.count("cherry"))   # 1
print(fruits.count("apple"))    # 2
print(fruits.count("pear"))     # 0

(5)len(可迭代对象)【公共方法】:求长度,即元素个数

# 示例
print(len(11))    # TypeError: object of type 'int' has no len()

print(len('xiaobai12'))   # 求字符个数
print(len(['aaaa', 'bbbb', "cccc", "dddd", 'eeee']))   # 求元素个数
print(len(('aaaa', 'bbbb', "cccc")))


量化小白,从0开始学量化! 1

著作权归文章作者所有。 未经作者允许禁止转载!

最新回复 ( 0 )
发新帖
0