Python - 访问元组项


在Python中,元组是一个序列。列表中的每个对象都可以通过其索引进行访问。索引从“0”开始。索引或元组中的最后一项是“length-1”。要访问元组中的值,请使用方括号与索引一起进行切片,以获得该索引处可用的值。

切片运算符从元组中获取一项或多项。

obj = tup1(i)

实施例1

将索引放在方括号内以检索其位置的项目。

tup1 = ("Rohan", "Physics", 21, 69.75)
tup2 = (1, 2, 3, 4, 5)

print ("Item at 0th index in tup1tup2: ", tup1[0])
print ("Item at index 2 in list2: ", tup2[2])

它将产生以下输出-

Item at 0th index in tup1: Rohan
Item at index 2 in tup2: 3

实施例2

Python 允许负索引与任何序列类型一起使用。“-1”索引指的是元组中的最后一项。

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 0th index in tup1: d
Item at index 2 in tup2: True

从元组中提取子元组

切片运算符从原始元组中提取子元组。

Subtup = tup1[i:j]

参数

  • i - 子组中第一项的索引

  • j - 子组中最后一项旁边的项目的索引

这将从tup1中返回从第i 项(j-1) 项的切片。

实施例3

看一下下面的例子 -

tup1 = ("a", "b", "c", "d")
tup2 = (25.50, True, -55, 1+2j)

print ("Items from index 1 to 2 in tup1: ", tup1[1:3])
print ("Items from index 0 to 1 in tup2: ", tup2[0:2])

它将产生以下输出-

Items from index 1 to 2 in tup1: ('b', 'c')
Items from index 0 to 1 in tup2: (25.5, True)

实施例4

切片时,操作数“i”和“j”都是可选的。如果不使用,“i”为 0,“j”为元组中的最后一项。切片时可以使用负索引。请参阅以下示例 -

tup1 = ("a", "b", "c", "d")
tup2 = (25.50, True, -55, 1+2j)
tup4 = ("Rohan", "Physics", 21, 69.75)
tup3 = (1, 2, 3, 4, 5)

print ("Items from index 1 to last in tup1: ", tup1[1:])
print ("Items from index 0 to 1 in tup2: ", tup2[:2])
print ("Items from index 2 to last in tup3", tup3[2:-1])
print ("Items from index 0 to index last in tup4", tup4[:])

它将产生以下输出-

Items from index 1 to last in tup1: ('b', 'c', 'd')
Items from index 0 to 1 in tup2: (25.5, True)
Items from index 2 to last in tup3: (3, 4)
Items from index 0 to index last in tup4: ('Rohan', 'Physics', 21, 69.75)