轻松上手,快乐学习!

Python 元组


元组

元组是一个集合是有序的和不可改变的。在Python中,元组是用圆括号编写的()

实例

创建一个元组:
thistuple = ("apple", "banana", "cherry")
print(thistuple)
运行实例 »

访问元组项

您可以通过参考方括号内的索引号来访问元组项:

实例

返回位置1的项目:
thistuple = ("apple", "banana", "cherry")
print(thistuple[1])
运行实例 »

更改元组值

创建元组后,您无法更改其值。元组是不可改变的

循环遍历元组

使用for循环遍历元组项。

实例

遍历项目并打印值:
thistuple = ("apple", "banana", "cherry")
for x in thistuple:
  print(x)
运行实例 »
Python For 循环章节 中了解for有关循环的更多信息。

检查项目是否存在

要确定元组中是否存在指定的项,请使用以下in关键字:

实例

检查元组中是否存在“apple”:
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" # This will raise an error
print(thistuple)
运行实例 »

删除项目

注意:您无法删除元组中的项目。
元组是不可更改的,因此您无法从中删除项目,但您可以完全删除元组:

实例

del关键字可以完全删除的元组:
thistuple = ("apple", "banana", "cherry")
del thistuple
print(thistuple) #this will raise an error because the tuple no longer exists
运行实例 »

tuple()构造函数

也可以使用tuple()构造函数来创建元组。

实例

使用tuple()方法创建一个元组:
thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets
print(thistuple)
运行实例 »

元组方法

Python有两个可以在元组上使用的内置方法。
方法 描述
count() 返回元组中指定值出现的次数
index() 返回指定值的位置