如何在 Tuple 中使用 Python Tuple?
programmingpythonserver side programming
Tuple 可以轻松地在 Tuple 中使用。Tuple 的任何项都可以是 Tuple。Tuple 是序列,即有序且不可变的对象集合。要在 Tuple 中访问 Tuple,请使用方括号和该特定内部 Tuple 的索引号。
Tuple 是不可变 Python 对象的序列。Tuple 是序列,就像列表一样。Tuple 和列表之间的主要区别在于,与列表不同,Tuple 不能更改。Tuple 使用括号,而列表使用方括号。
创建一个基本 Tuple
让我们首先创建一个包含整数元素的基本 Tuple,然后再转向 Tuple 中的 Tuple
示例
# 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 个元素的 Tuple。其中一个元素实际上是一个 Tuple,即 (18, 19, 20),但 len() 方法将其计为一个 Tuple。
在 Tuple 中访问 Tuple
在此示例中,我们将创建一个包含整数元素的 Tuple。在其中,我们将添加一个内部 Tuple,并使用方括号和特定索引号访问它 -
示例
# 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