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 - subtup中第一个项的索引
-
j - subtup中最后一项的索引的下一个位置
这将返回一个切片,切片从第i个到第(j-1)个项的tup1中。
示例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)