在Python中,元组是一种不可变的数据类型,类似于列表,但元组一旦创建就不能被修改。元组使用小括号 () 表示,其中的元素用逗号 , 分隔。与列表不同,元组是不可变的,这意味着你不能在创建后添加、删除或修改元素。

下面是一些关于元组的基本操作:

创建元组:
my_tuple = (1, 2, 3)

访问元组元素:
print(my_tuple[0])  # 输出 1

切片:
subset = my_tuple[1:3]  # 创建一个包含元组索引 1 到 2 的子元组 (2, 3)

元组拼接:
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
concatenated_tuple = tuple1 + tuple2  # 结果为 (1, 2, 3, 4, 5, 6)

元组长度:
length = len(my_tuple)  # 输出元组的长度,这里为 3

元组中是否包含某个元素:
is_present = 2 in my_tuple  # 输出 True,因为2在元组中

元组解包:
a, b, c = my_tuple
# 现在 a=1, b=2, c=3

元组在一些情况下比列表更适用,特别是当你希望数据在创建后不可更改时。


转载请注明出处:http://www.pingtaimeng.com/article/detail/13325/Python 基础