Files
python/13-17/09tuple.py
T
2026-05-06 11:21:42 +08:00

103 lines
3.3 KiB
Python

# 元组 是一个有序、不可变的集合,可以存储任意数量、任意类型的元素。
# 有序:元素有固定的位置(索引),按添加的顺序排列。
# 不可变:创建后,不能修改元组的内容(不能增、删、改元素)。
# 异构:一个元组中可以包含不同类型的数据。
# 核心特性:不可变性是元组与列表最根本的区别!
# 创建方式
# 使用()
empty_tuple = ()
print(empty_tuple)
numers = (1, 2, 3, 4, 5)
fruits = ("apple", "banana", "orange")
mixed = (
"Hello",
1,
[
1,
2,
],
True,
)
print(numers)
print(fruits)
print(mixed)
# 使用tuple构造函数
# tuple() 是 Python 的一个内置函数,可以把可迭代对象(如列表、字符串、字典、集合等)转化为元组。这种方式更适合在已知有可迭代数据时创建元组,例如将列表转换为元组,或将字符串的每个字符作为元组的一个元素。
# 如果不传参数,tuple() 会返回一个空的元组。
list_data = [1, 2, 3]
tuple_from_list = tuple(list_data)
print(tuple_from_list) # (1, 2, 3)
tuple_from_string = tuple("abc")
print(tuple_from_string) # ('a', 'b', 'c')
# 创建空元组
another_enmpy_tuple = tuple()
print(another_enmpy_tuple)
# 特殊情况,单个元素的元组
# 创建单个元素的元组,需要在元组后面加,否则python会认为他是括号表达式
a_tuple = (1,)
print(a_tuple)
# 访问元组
# 通过索引
fruits = ("apple", "banana", "orange", "grape")
print(fruits[0]) # "apple" - 第一个元素
print(fruits[1]) # "banana" - 第二个元素
print(fruits[-1]) # "grape" - 最后一个元素
print(fruits[-2]) # "orange" - 倒数第二个元素
# 通过切片
numbers = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
print(numbers[2:5]) # (2, 3, 4) # 索引2到5(不含5)
print(numbers[:4]) # (0, 1, 2, 3) # 从开始到索引4
print(numbers[5:]) # (5, 6, 7, 8, 9) # 从索引5到结束
print(numbers[::2]) # (0, 2, 4, 6, 8) # 每隔一个取一个元素
print(numbers[::-1]) # (9, 8, 7, 6, 5, 4, 3, 2, 1, 0) # 反转元组
# 元组的不可变
fruits = ("apple", "banana", "cherry")
# fruits[0] = "abc" # TypeError: 'tuple' object does not support item assignment
# 如何修改元组
# 由于元组不可变,不能直接修改,但可以创建新的元组
# 直接重新赋值
fruits = ("apple", "banana", "cherry")
fruits = ("apple", "pear", "banana", "cherry") # 重新创建新元组
print(fruits) # ('apple', 'pear', 'banana', 'cherry')
# 通过拼接
fruits = ("apple", "banana", "cherry")
new_fruits = fruits[:1] + ("pear",) + fruits[1:]
print(new_fruits)
# 元组的操作与方法
# 列表操作类似,元组也支持以下常用操作(但所有操作不会改变原元组,而是产生新元组或返回新结果):
# 连接(拼接):用加号 + 组合两个元组,得到新元组。
# 重复:用乘号 * 重复元组若干次,得到新元组。
# 成员测试:用 in 或 not in 判断元素是否存在于元组中,返回布尔值。
# 获取长度:len(tuple) 返回元组包含的元素数量。
# 拼接
tuple1 = (1, 2)
tuple2 = (3, 4)
tuple3 = tuple1 + tuple2
print(tuple3) # (1, 2,3,4)
# 重复
tuple4 = tuple3 * 2
print(tuple4) # (1, 2, 3, 4, 1, 2, 3, 4)
# 是否存在
fruits = ("apple", "banana")
print("apple" in fruits) # True
# 获取长度
print(len(fruits)) # 2