【问题标题】: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() 方法?
  • 这明明是功课,怎么还不早关!

标签: python python-3.x


【解决方案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))
    

    【讨论】:

      猜你喜欢
      • 2017-12-01
      • 2016-06-09
      • 1970-01-01
      • 2018-10-11
      • 1970-01-01
      • 2023-01-07
      • 1970-01-01
      • 1970-01-01
      • 2014-11-10
      相关资源
      最近更新 更多