如何在 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
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP