此 Python 函数用于查找给定列表中某项的索引。在本节中,我们将讨论如何使用列表索引方法,并提供实际示例,其语法为:
list.index(list_item)
Python 索引列表函数示例
它从给定的列表中查找某个项的索引,下面的代码查找整数项 10 和 50 的位置。
a = [20, 30, 10, 40, 10, 50, 20] print(a.index(10)) print(a.index(50))
2
5
在此 函数 示例中,我们声明了一个字符串 列表。接下来,我们使用此函数查找 Orange 和 Kiwi 的位置。
Fruits = ['Apple', 'Orange', 'Banana', 'Kiwi', 'Grape']
print("Orange = ", Fruits.index('Orange'))
print("Kiwi = ", Fruits.index('Kiwi'))
Orange = 1
Kiwi = 3
这是另一个用于返回位置的列表索引函数示例。
Fruits = ['Apple', 'Orange', 'Banana', 'Kiwi', 'Grape', 'Blackberry']
numbers = [9, 4, -5, 0, 22, -1, 2, 14]
print(Fruits)
print(numbers)
print()
print('Kiwi = ', Fruits.index('Kiwi'))
print('Orange = ', Fruits.index('Orange'))
print('Grape = ', Fruits.index('Grape'))
print()
print('0 = ', numbers.index(0))
print('2 = ', numbers.index(2))
print('-1 = ', numbers.index(-1))
['Apple', 'Orange', 'Banana', 'Kiwi', 'Grape', 'Blackberry']
[9, 4, -5, 0, 22, -1, 2, 14]
Kiwi = 3
Orange = 1
Grape = 4
0 = 3
2 = 6
-1 = 5
列表索引示例 2
此 程序 与第一个示例相同。但是,这次我们允许用户输入长度。接下来,我们使用 For Loop 将这些数字追加到 Python 中。
intIndexList = []
number = int(input("Please enter the Total Number of List Elements: "))
for i in range(1, number + 1):
value = int(input("Please enter the Value of %d Element : " %i))
intIndexList.append(value)
item = int(input("Please enter the Item that you want to Find: "))
print("The Index Position of Given Item = ", intIndexList.index(item))

此程序允许用户输入自己的字符串或单词,然后查找指定单词的索引位置。
str1 = []
number = int(input("Please enter the Total Number: "))
for i in range(1, number + 1):
value = input("%d Element : " %i)
str1.append(value)
item = input("Please enter the Item that you want to Find: ")
print("The Position of Given Item = ", str1.index(item))
Please enter the Total Number: 4
1 Element : Apple
2 Element : Kiwi
3 Element : Banana
4 Element : Orange
Please enter the Item that you want to Find: Banana
The Position of Given Item = 2