Python 访问列表项
在Python中,列表是一个序列。可以通过索引访问列表中的每个对象。索引从0开始。索引或者列表中的最后一个项是”length-1″。要访问列表中的值,可以使用方括号进行切片,并使用索引或索引来获得该索引处的值。
切片运算符从列表中获取一个或多个项。将索引放在方括号中以检索其位置处的项。
obj = list1[i]
示例1
看一下下面的示例-
list1 = ["Rohan", "Physics", 21, 69.75]
list2 = [1, 2, 3, 4, 5]
print ("Item at 0th index in list1: ", list1[0])
print ("Item at index 2 in list2: ", list2[2])
它将产生以下 输出 -
Item at 0th index in list1: Rohan
Item at index 2 in list2: 3
Python允许在任何序列类型中使用负索引。”-1″索引表示列表中的最后一项。
示例2
让我们看另一个例子 −
list1 = ["a", "b", "c", "d"]
list2 = [25.50, True, -55, 1+2j]
print ("Item at 0th index in list1: ", list1[-1])
print ("Item at index 2 in list2: ", list2[-3])
它将产生以下 输出 。 −
Item at 0th index in list1: d
Item at index 2 in list2: True
切片操作符从原始列表中提取子列表。
Sublist = list1[i:j]
参数
- i −子列表中第一项的索引
-
j −子列表中最后一项的下一个项的索引
将返回从列表1的第i项到第(j-1)项的切片。
示例3
在切片过程中,”i”和”j”两个运算数都是可选的。如果不使用,”i”默认为0,”j”为列表中的最后一项。切片中可以使用负索引。请看下面的例子 −
list1 = ["a", "b", "c", "d"]
list2 = [25.50, True, -55, 1+2j]
print ("Items from index 1 to 2 in list1: ", list1[1:3])
print ("Items from index 0 to 1 in list2: ", list2[0:2])
它将产生以下 输出 −
Items from index 1 to 2 in list1: ['b', 'c']
Items from index 0 to 1 in list2: [25.5, True]
示例4
list1 = ["a", "b", "c", "d"]
list2 = [25.50, True, -55, 1+2j]
list4 = ["Rohan", "Physics", 21, 69.75]
list3 = [1, 2, 3, 4, 5]
print ("Items from index 1 to last in list1: ", list1[1:])
print ("Items from index 0 to 1 in list2: ", list2[:2])
print ("Items from index 2 to last in list3", list3[2:-1])
print ("Items from index 0 to index last in list4", list4[:])
它将产生以下 输出 –
Items from index 1 to last in list1: ['b', 'c', 'd']
Items from index 0 to 1 in list2: [25.5, True]
Items from index 2 to last in list3 [3, 4]
Items from index 0 to index last in list4 ['Rohan', 'Physics', 21, 69.75]