如何在 Python 中使用元組巢狀元組?


元組可以很容易地巢狀在另一個元組中。元組的任何元素都可以是另一個元組。元組是序列,即有序且不可變的物件集合。要訪問巢狀元組中的元組,可以使用方括號和該特定內部元組的索引號。

元組是不可變的 Python 物件的序列。元組與列表一樣,都是序列。元組和列表之間的主要區別在於,與列表不同,元組無法更改。元組使用括號,而列表使用方括號。

建立基本元組

讓我們首先建立一個包含整數元素的基本元組,然後轉向巢狀元組。

示例

# Creating a Tuple mytuple = (20, 40, 60, 80, 100) # Displaying the Tuple print("Tuple = ",mytuple) # Length of the Tuple print("Tuple Length= ",len(mytuple))

輸出

Tuple = (20, 40, 60, 80, 100)
Tuple Length= 5

建立巢狀元組

在這個例子中,我們將建立一個包含整數元素的元組。在其中,我們將新增一個內部元組 (18, 19, 20) -

示例

# Creating a Tuple mytuple = (20, 40, (18, 19, 20), 60, 80, 100) # Displaying the Tuple print("Tuple = ",mytuple) # Length of the Tuple print("Tuple Length= ",len(mytuple))

輸出

Tuple = (20, 40, (18, 19, 20), 60, 80, 100)
Tuple Length= 6

上面,我們建立了一個總共有 6 個元素的元組。其中一個元素實際上是一個元組,即 (18, 19, 20),但由 len() 方法計算為一個元組。

訪問巢狀元組

在這個例子中,我們將建立一個包含整數元素的元組。在其中,我們將新增一個內部元組,並使用方括號和特定的索引號訪問它 -

示例

# Creating a Tuple mytuple = (20, 40, (18, 19, 20), 60, 80, 100) # Displaying the Tuple print("Tuple = ",mytuple) # Length of the Tuple print("Tuple Length= ",len(mytuple)) # Display the Tuple within a Tuple print("Tuple within a Tuple = ",mytuple[2])

輸出

Tuple = (20, 40, (18, 19, 20), 60, 80, 100)
Tuple Length= 6
Tuple within a Tuple = (18, 19, 20)

訪問內部元組的特定元素

在這個例子中,我們將建立一個包含字串元素的元組。在其中,我們將新增一個內部元組。這些元素使用方括號和特定的索引號進行訪問。但是,如果您想訪問內部元組的元素,請使用它們的內部索引 -

示例

# Creating a List mytuple = ("Rassie", "Aiden", ("Dwaine", "Beuran", "Allan"), "Peter") # Displaying the Tuple print("Tuple = ",mytuple) # List length print("Tuple = ",len(mytuple)) # Display the Tuple within a Tuple print("Tuple within a Tuple = ",mytuple[2]) # Display the inner tuple elements one-by-one Tuple within a Tuple print("Inner Tuple 1st element = ",mytuple[2][0]) print("Inner Tuple 2nd element = ",mytuple[2][1]) print("Inner Tuple 3rd element = ",mytuple[2][2])

輸出

Tuple = ('Rassie', 'Aiden', ('Dwaine', 'Beuran', 'Allan'), 'Peter')
Tuple = 4
Tuple within a Tuple = ('Dwaine', 'Beuran', 'Allan')
Inner Tuple 1st element = Dwaine
Inner Tuple 2nd element = Beuran
Inner Tuple 3rd element = Allan

更新於: 2022年8月11日

9K+ 瀏覽量

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告