编写在数字数组中查找元素索引的函数[重复]
Posted
技术标签:
【中文标题】编写在数字数组中查找元素索引的函数[重复]【英文标题】:Write the function that finds the index of an element in array of numbers [duplicate] 【发布时间】:2019-06-08 18:59:42 【问题描述】:我这样做是为了找到数字数组的最小值:
lst = [3, 71, 420, 14]
print ("Min number in array:", min(lst))
但是如何在数字数组中找到元素的索引?
【问题讨论】:
通过使用列表中的.index()
方法?
这明明是功课,怎么还不早关!
【参考方案1】:
您可以使用enumerate
为列表中的每个项目生成索引,并为min
函数提供一个键函数,该函数使用enumerate
生成的序列中每个元组的第二个项目,最后,使用[0]
提取min
返回的最小值的item的索引:
from operator import itemgetter
print(min(enumerate(lst), key=itemgetter(1))[0])
这输出:0
(您的示例列表中3
的索引)
【讨论】:
【参考方案2】:我能想到的最简单的解决方案是通过索引:
lst.index(min(lst))
【讨论】:
以上是关于编写在数字数组中查找元素索引的函数[重复]的主要内容,如果未能解决你的问题,请参考以下文章