访问 Python 列表中的索引和值

pythonserver side programmingprogramming

当我们使用 Python 列表时,需要访问其在不同位置的元素。在本文中,我们将了解如何获取列表中特定元素的索引。

使用 list.Index

以下程序获取给定列表中不同元素的索引值。我们将元素的值作为参数提供,索引函数返回该元素的索引位置。

示例

listA = [11, 45,27,8,43]
# Print index of '45'
print("Index of 45: ",listA.index(45))
listB = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat']
# Print index of 'Wed'
print("Index of Wed: ",listB.index('Wed'))

输出

运行上述代码得到以下结果 −

('Index of 45: ', 1)
('Index of Wed: ', 3)

使用范围和长度

在下面的程序中,我们遍历列表的每个元素并应用列表函数内部 for 循环来获取索引。

示例

listA = [11, 45,27,8,43]
#给定列表
print("给定列表:",listA)
# 打印所有索引和值
print("索引和值:")
print ([list((i, listA[i])) for i in range(len(listA))])

输出

运行上述代码得到以下结果 −

Given list: [11, 45, 27, 8, 43]
Index and Values:
[[0, 11], [1, 45], [2, 27], [3, 8], [4, 43]]

使用枚举

枚举函数本身跟踪列表中元素的索引位置和值。因此,当我们将枚举函数应用于列表时,它会同时输出索引和值。

示例

listA = [11, 45,27,8,43]
#给定列表
print("给定列表:",listA)
# 打印所有索引和值
print("Index and Values: ")
for index, value in enumerate(listA):
   print(index, value)

输出

运行上述代码得到以下结果 −

Given list: [11, 45, 27, 8, 43]
Index and Values:
0 11
1 45
2 27
3 8
4 43

相关文章