Python 元組

元組(Tuple)

元組是有序且不可更改的集合。在 Python 中,元組是用圓括號編寫的。

實例

創建元組:

thistuple = ("apple", "banana", "cherry")
print(thistuple)

運行實例

訪問元組項目

您可以通過引用方括號內的索引號來訪問元組項目:

實例

打印元組中的第二個項目:

thistuple = ("apple", "banana", "cherry")
print(thistuple[1])

運行實例

負索引

負索引表示從末尾開始,-1 表示最后一個項目,-2 表示倒數第二個項目,依此類推。

實例

打印元組的最后一個項目:

thistuple = ("apple", "banana", "cherry")
print(thistuple[-1])

運行實例

索引范圍

您可以通過指定范圍的起點和終點來指定索引范圍。

指定范圍后,返回值將是帶有指定項目的新元組。

實例

返回第三、第四、第五個項目:

thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[2:5])

運行實例

注釋:搜索將從索引 2(包括)開始,到索引 5(不包括)結束。

請記住,第一項的索引為 0。

負索引范圍

如果要從元組的末尾開始搜索,請指定負索引:

實例

此例將返回從索引 -4(包括)到索引 -1(排除)的項目:

thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[-4:-1])

運行實例

更改元組值

創建元組后,您將無法更改其值。元組是不可變的,或者也稱為恒定的。

但是有一種解決方法。您可以將元組轉換為列表,更改列表,然后將列表轉換回元組。

實例

把元組轉換為列表即可進行更改:

x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)

運行實例

遍歷元組

您可以使用 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" # 會引發錯誤
print(thistuple)

運行實例

創建有一個項目的元組

如需創建僅包含一個項目的元組,您必須在該項目后添加一個逗號,否則 Python 無法將變量識別為元組。

實例

單項元組,別忘了逗號:

thistuple = ("apple",)
print(type(thistuple))
#不是元組
thistuple = ("apple")
print(type(thistuple))

運行實例

刪除項目

注釋:您無法刪除元組中的項目。

元組是不可更改的,因此您無法從中刪除項目,但您可以完全刪除元組:

實例

del 關鍵字可以完全刪除元組:

thistuple = ("apple", "banana", "cherry")
del thistuple
print(thistuple) # 這會引發錯誤,因為元組已不存在。

運行實例

合并兩個元組

如需連接兩個或多個元組,您可以使用 + 運算符:

實例

合并這個元組:

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

運行實例

tuple() 構造函數

也可以使用 tuple() 構造函數來創建元組。

實例

使用 tuple() 方法來創建元組:

thistuple = tuple(("apple", "banana", "cherry")) # 請注意雙括號
print(thistuple)

運行實例

元組方法

Python 提供兩個可以在元組上使用的內建方法。

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