Python元组

#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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值