如何在 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日

9000+ 浏览量

启动你的职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.