数组是一种数据结构,用于按顺序存储相同数据类型的元素。并且存储的元素由索引值来标识。 Python 没有特定的数据结构来表示数组。但是,我们可以使用 List 数据结构或 Numpy 模块来处理数组。
在本文中,我们看到了多种获取指定项在数组中第一次出现的索引的方法。
输入输出场景
现在让我们看看一些输入输出场景。
假设我们有一个包含很少元素的输入数组。在输出中,我们将获取第一次出现的指定值的索引。
立即学习“Python免费学习笔记(深入)”;
Input array:[1, 3, 9, 4, 1, 7]specified value = 9Output:2
登录后复制
指定的元素 9 仅在数组中出现一次,该值的结果索引为 2。
Input array:[1, 3, 6, 2, 4, 6]specified value = 6Output:2
登录后复制
给定元素 6 在数组中出现了两次,第一次出现的索引值为 2。
使用list.index()方法
list.index() 方法可帮助您查找数组中给定元素第一次出现的索引。如果列表中存在重复元素,则返回该元素的第一个索引。以下是语法 –
list.index(element, start, end)
登录后复制
第一个参数是我们想要获取索引的元素,第二个和第三个参数是可选参数,从哪里开始和结束对给定元素的搜索。
list.index() 方法返回一个整数值,它是我们传递给该方法的给定元素的索引。
示例
在上面的示例中,我们将使用index()方法。
# creating arrayarr = [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 itemitem_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 arrayarr = [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 itemfor 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 arrayarr = np.array([2, 4, 6, 8, 1, 3, 9, 6])print("Original array: ", arr)specified_index = 6index = np.where(arr == specified_index)# Get index of the first occurrence of the specified itemprint('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程序用于在数组中查找指定项的第一次出现的索引的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2225484.html