#python元组(Tuple)
#在 Python 中,元组是用圆括号编写的
thistuple = ("apple","banana","cherry")
print(thistuple)
thistuple = ("apple","banana","cherry")
print(thistuple[1])
#负索引
thistuple = ("apple","banana","cherry")
print(thistuple[-1])#打印元组的最后一个项目
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[2:5])
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[-4:-1])
#更改元组值
#创建元组后,您将无法更改其值。元组是不可变的,或者也称为恒定的。
#但是有一种解决方法。您可以将元组转换为列表,更改列表,然后将列表转换回元组。
x = ("apple","banana","cherry")
y = list(x)
print(y)
y[1] = "kiwi"
x = tuple(y)
print(x)
#遍历元组
#使用for循环遍历元组项目
thistuple = ("apple","banana","cherry")
for x in thistuple:
print(x)
#检查项目是否存在
#要确定元组中是否存在指定的项,请使用in关键字
thistuple = ("apple","banana","cherry")
if "apple" in thistuple:
print("Yes,'apple' is in the fruits tuple")
#元组长度
#要确定元组有多少项,请使用len()方法
thistuple = ("apple","banana","cherry")
print(len(thistuple))
#添加项目
#元组一旦创建,您就无法向其添加项目。元组是不可改变的
# thistuple = ("apple", "banana", "cherry")
# thistuple[3] = "orange" # 会引发错误
#print(thistuple)
#创建有一个项目的元组
#单项元组,必须在该项目后添加一个逗号,否则Python无法将变量识别为元组
thistuple = ("apple",)
print(type(thistuple))#<class 'tuple'>
thistuple = ("apple")#不是元组
print(type(thistuple))#<class 'str'>
#删除项目
#元组是不可更改的,您无法从中删除项目,但您可以完全删除元组
thistuple = ("apple","banana","cherry")
del thistuple
#print(thistuple)#这会引发错误,因为元组已不存在
#合并两个元组
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)
#tuple()构造函数
#也可以使用tuple()构造函数来创建元组
thistuple = tuple(("apple","banana","cherry"))
print(thistuple)