Python 元组

元组(Tuple)

元组是有序且不可更改的集合。在 Python 中,元组是用圆括号编写的。

创建元组:

  1. thistuple = ("apple", "banana", "cherry")
  2. print(thistuple)

访问元组项目

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

打印元组中的第二个项目:

  1. thistuple = ("apple", "banana", "cherry")
  2. print(thistuple[1])
负索引

负索引表示从末尾开始,-1 表示最后一个项目,-2 表示倒数第二个项目,依此类推。

打印元组的最后一个项目:

  1. thistuple = ("apple", "banana", "cherry")
  2. print(thistuple[-1])
索引范围

您可以通过指定范围的起点和终点来指定索引范围。

指定范围后,返回值将是带有指定项目的新元组。

返回第三、第四、第五个项目:

  1. thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
  2. print(thistuple[2:5])
  3. #This will return the items from position 2 to 5.
  4. #Remember that the first item is position 0,
  5. #and note that the item in position 5 is NOT included

注释:搜索将从索引 2(包括)开始,到索引 5(不包括)结束。

请记住,第一项的索引为 0。

负索引范围

如果要从元组的末尾开始搜索,请指定负索引:

此例将返回从索引 -4(包括)到索引 -1(排除)的项目:

  1. thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
  2. print(thistuple[-4:-1])
  3. #Negative indexing means starting from the end of the tuple.
  4. #This example returns the items from index -4 (included) to index -1 (excluded)
  5. #Remember that the last item has the index -1,

更改元组值

创建元组后,您将无法更改其值。元组是不可变的,或者也称为恒定的。

但是有一种解决方法。您可以将元组转换为列表,更改列表,然后将列表转换回元组。

把元组转换为列表即可进行更改:

  1. x = ("apple", "banana", "cherry")
  2. y = list(x)
  3. y[1] = "kiwi"
  4. x = tuple(y)
  5. print(x)

遍历元组

您可以使用 for 循环遍历元组项目。

遍历项目并打印值:

  1. thistuple = ("apple", "banana", "cherry")
  2. for x in thistuple:
  3. print(x)

您将在 Python For 循环 这一章中学习有关 for 循环的更多知识。


检查项目是否存在

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

检查元组中是否存在 "apple":

  1. thistuple = ("apple", "banana", "cherry")
  2. if "apple" in thistuple:
  3. print("Yes, 'apple' is in the fruits tuple")

元组长度

要确定元组有多少项,请使用 len() 方法:

打印元组中的项目数量:

  1. thistuple = ("apple", "banana", "cherry")
  2. print(len(thistuple))

添加项目

元组一旦创建,您就无法向其添加项目。元组是不可改变的。

您无法向元组添加项目:

  1. thistuple = ("apple", "banana", "cherry")
  2. thistuple[3] = "orange" # This will raise an error
  3. print(thistuple)

创建有一个项目的元组

如需创建仅包含一个项目的元组,您必须在该项目后添加一个逗号,否则 Python 无法将变量识别为元组。

单项元组,别忘了逗号:

  1. thistuple = ("apple",)
  2. print(type(thistuple))
  3. #NOT a tuple
  4. thistuple = ("apple")
  5. print(type(thistuple))

删除项目

注释:您无法删除元组中的项目。

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

del 关键字可以完全删除元组:

  1. thistuple = ("apple", "banana", "cherry")
  2. del thistuple
  3. print(thistuple) #this will raise an error because the tuple no longer exists

合并两个元组

如需连接两个或多个元组,您可以使用 + 运算符:

合并这个元组:

  1. tuple1 = ("a", "b" , "c")
  2. tuple2 = (1, 2, 3)
  3. tuple3 = tuple1 + tuple2
  4. print(tuple3)

tuple() 构造函数

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

使用 tuple() 方法来创建元组:

  1. thistuple = tuple(("apple", "banana", "cherry"))
  2. print(thistuple)

元组方法

Python 提供两个可以在元组上使用的内建方法。

方法描述
count()返回元组中指定值出现的次数。
index()在元组中搜索指定的值并返回它被找到的位置。