Python 查找数组中指定项的第一次出现的索引
数组是一种数据结构,用于按顺序存储相同数据类型的元素。并且存储的元素由索引值标识。Python没有特定的数据结构来表示数组。但是,我们可以使用List数据结构或Numpy模块来处理数组。
在本文中,我们将看到多种方法来获取数组中指定项的第一次出现的索引。
输入输出情况
现在让我们来看一些输入输出的情况。
假设我们有一个带有几个元素的输入数组。在输出中,我们将得到指定值第一次出现的索引。
Input array:
[1, 3, 9, 4, 1, 7]
specified value = 9
Output:
2
指定的元素 9 在数组中只出现一次,并且该值的结果索引为2。
Input array:
[1, 3, 6, 2, 4, 6]
specified value = 6
Output:
2
给定的元素6在数组中出现了两次,并且第一次出现的索引值是2。
使用list.index()方法
list.index()方法帮助你找到数组中给定元素的第一次出现的索引。如果列表中有重复的元素,则返回该元素的第一个索引。以下是语法:
list.index(element, start, end)
第一个参数是我们想要获取索引的元素,第二个和第三个参数是可选参数,表示我们要在何处开始和结束对给定元素的搜索。
list.index()方法返回一个整数值,即我们传递给该方法的元素的索引。
示例
在上面的示例中,我们将使用index()方法。
# creating array
arr = [1, 3, 6, 2, 4, 6]
print ("The original array is: ", arr)
print()
specified_item = 6
# Get index of the first occurrence of the specified item
item_index = arr.index(specified_item)
print('The index of the first occurrence of the specified item is:',item_index)
输出
The original array is: [1, 3, 6, 2, 4, 6]
The index of the first occurrence of the specified item is: 2
给定的值6在数组中出现了两次,但是index()方法只返回第一次出现的值的索引。
使用for循环
同样地,我们可以使用for循环和if条件来获取数组中出现在第一个位置的指定项的索引。
示例
在这里,我们将使用for循环遍历数组元素。
# creating array
arr = [7, 3, 1, 2, 4, 3, 8, 5, 4]
print ("The original array is: ", arr)
print()
specified_item = 4
# Get the index of the first occurrence of the specified item
for index in range(len(arr)):
if arr[index] == specified_item:
print('The index of the first occurrence of the specified item is:',index)
break
输出
The original array is: [7, 3, 1, 2, 4, 3, 8, 5, 4]
The index of the first occurrence of the specified item is: 4
给定的值4在数组中重复出现,但上面的示例只返回第一次出现的值的索引。
使用numpy.where()
numpy.where()方法用于根据给定的条件筛选数组元素。通过使用该方法,我们可以得到给定元素的索引。以下是语法:
numpy.where(condition, [x, y, ]/)
示例
在这个示例中,我们将使用numpy.where()方法与条件。
import numpy as np
# creating array
arr = np.array([2, 4, 6, 8, 1, 3, 9, 6])
print("Original array: ", arr)
specified_index = 6
index = np.where(arr == specified_index)
# Get index of the first occurrence of the specified item
print('The index of the first occurrence of the specified item is:',index[0][0])
输出
Original array: [2 4 6 8 1 3 9 6]
The index of the first occurrence of the specified item is: 2
条件 arr == specified_index
检查numpy数组中给定元素,并返回满足给定条件的元素或True的数组。通过这个结果数组,我们可以通过使用index[0
][0]来获得第一次出现的索引。