元组

元组

元组是有序不可更改的集合

1
2
3
4
5
6
7
8
9
10
#创建元组
thistuple = ("apple", "banana", "cherry")
#遍历元组
for x in thistuple:
print(x)
#检查项目是否存在
if "apple" in thistuple:
print("yes")
#确定元组长度
print(len(thistuple))

元组的创建

需要注意的是,在创建只有一个项目的元组时,需要在其后加 , 否则系统无法识别其是否为元组

1
2
thistuple = ("apple") #不是元组,而是字符串
thistuple = ("apple", ) #是元组

元组的增、删、改

元组一旦创建,就无法添加项目,元组是无法改变的
如果想要对其进行修改操作,可以强制转型为list,更改之后在强制转型回tuple。
元组无法实现删除操作,但可以删除整个元组

1
2
3
4
5
6
7
8
#修改
thistuple = ("apple", "banana", "cherry")
list(thistuple)
thistuple[2] = "orange"
tuple(thistuple)
print thistuple
#删除元组
del thistuple

元组的合并

如果想连接两个以上的元组,可以通过+运算符进行连接

1
print(tuple1 + tuple2)

元组方法

Python提供两个元组上的内建方法

方法名 功能
count() 返回元组中指定值出现的次数
index() 返回元组中指定值的索引号


元组
http://blog.170827.xyz/2024/02/29/元组/
作者
XIAOBAI
发布于
2024年2月29日
许可协议