微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python程序用于在数组中查找指定项的第一次出现的索引

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 ==指定索引检查numpy数组中的给定元素,并返回一个包含满足给定条件或True的元素的数组。从结果数组中,我们可以使用索引[0][0]获取第一次出现的索引。

以上就是Python程序用于在数组中查找指定项的第一次出现的索引的详细内容,更多请关注编程之家其它相关文章

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐