访问元组项
访问 Python 元组中值的最常见方法是使用索引,我们只需要将要检索的元素的索引指定为方括号 [] 表示法。
除了索引之外,Python 还提供了各种其他方法来访问元组项,例如切片、负索引、从元组中提取子元组等。让我们一一来了解一下 -
使用索引访问 Tuples 项
元组中的每个元素都对应一个索引。第一个元素的索引从 0 开始,每个后续元素的索引递增 1。元组中最后一项的索引始终为 “length-1”,其中 “length” 表示元组中的项总数。要访问元组的元素,我们只需要指定我们需要访问/检索的项目的索引,如下所示 -
tuple[3]
例
以下是访问具有切片索引的 Tuples 项的基本示例 -
tuple1 = ("Rohan", "Physics", 21, 69.75)
tuple2 = (1, 2, 3, 4, 5)
print ("Item at 0th index in tuple1: ", tuple1[0])
print ("Item at index 2 in tuple2: ", tuple2[2])
它将产生以下输出 -
Item at index 2 in tuple2: 3
访问具有负索引的 Tuples 项
Python 中的负索引用于访问元组末尾的元素,其中 -1 表示最后一个元素,-2 表示倒数第二个元素,依此类推。
我们还可以通过使用负整数来表示从元组末尾开始的位置,从而访问具有负索引的元组项。
例在下面的示例中,我们将访问具有负索引的元组项目 -
tup1 = ("a", "b", "c", "d")
tup2 = (25.50, True, -55, 1+2j)
print ("Item at 0th index in tup1: ", tup1[-1])
print ("Item at index 2 in tup2: ", tup2[-3])
我们得到的输出如下所示 -
Item at index 2 in tup2: True
访问具有负索引的 Tuples 项范围
元组项范围是指使用切片从元组访问元素的子集。因此,我们可以通过使用 Python 中的切片操作来访问一系列具有负索引的元组项。
例在下面的示例中,我们通过使用负索引来访问一系列元组项目 -
tup1 = ("a", "b", "c", "d")
tup2 = (1, 2, 3, 4, 5)
print ("Items from index 1 to last in tup1: ", tup1[1:])
print ("Items from index 2 to last in tup2", tup2[2:-1])
它将产生以下输出 -
Items from index 2 to last in tup2: (3, 4)
使用 Slice 运算符访问元组项
Python 中的 slice 运算符用于从元组中获取一个或多个项目。我们可以通过指定要提取的索引范围,使用 slice 运算符访问元组项。它使用以下语法 -
[start:stop]
哪里
- start 是起始索引(含)。
- stop 是结束索引 (不包括)。
例
在下面的示例中,我们将检索从 “tuple1” 中索引 1 到最后一个和 “tuple2” 中索引 0 到 1 的子元组,并检索 “tuple3” 中的所有元素 -
tuple1 = ("a", "b", "c", "d")
tuple2 = (25.50, True, -55, 1+2j)
tuple3 = (1, 2, 3, 4, 5)
tuple4 = ("Rohan", "Physics", 21, 69.75)
print ("Items from index 1 to last in tuple1: ", tuple1[1:])
print ("Items from index 0 to 1 in tuple2: ", tuple2[:2])
print ("Items from index 0 to index last in tuple3", tuple3[:])
以下是上述代码的输出 -
Items from index 0 to 1 in tuple2: (25.5, True)
Items from index 0 to index last in tuple3 ('Rohan', 'Physics', 21, 69.75)
从 Tuple 访问 Sub Tuple
子元组是元组的一部分,它由原始元组中的连续元素序列组成。
我们可以通过使用具有适当 start 和 stop 索引的 slice 运算符从元组访问子元组。它使用以下语法 -
my_tuple[start:stop]
哪里
- start 是起始索引(含)。
- stop 是 subtuples 的结束索引(不包括)。
如果我们没有提供任何索引,则 slice 运算符默认从索引 0 开始,并在元组中的最后一项处停止。
例在此示例中,我们使用切片运算符从 “tuple1” 中的索引 “1 to 2” 和“tuple2” 中的索引 “0 to 1” 获取子元组 −
tuple1 = ("a", "b", "c", "d")
tuple2 = (25.50, True, -55, 1+2j)
print ("Items from index 1 to 2 in tuple1: ", tuple1[1:3])
print ("Items from index 0 to 1 in tuple2: ", tuple2[0:2])
获得的输出如下 -
Items from index 0 to 1 in tuple2: (25.5, True)