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 - 子列表中最后一项旁边的项目的索引

这将返回list1中第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]