【问题标题】:Locate the index of largest value in an array python [duplicate]在数组python中找到最大值的索引[重复]
【发布时间】:2014-04-12 02:27:59
【问题描述】:

如何定位用户输入的数组中最大值的索引?这是我所拥有的:

def main():
   numbers = eval(input("Give me an array of numbers: "))
   largest = numbers[0]

【问题讨论】:

  • @ajm475du 他想要索引并且排序会改变所说的索引。
  • 我真的真的喜欢这个尝试。
  • 不想因使用sorted 的想法而受到“信任”。这是由于之前的评论者明智地删除了该评论。然而,我在应用它方面做得很糟糕。哈。

标签: python


【解决方案1】:
max_index, max_value = max(enumerate(numbers), key=lambda pair: pair[1])

这样做:

  • enumerate(numbers) 生成(索引、值)对
  • lambda 对:pair[1] 接受这样一个对并返回它的值部分
  • max() 返回最大对 out enumerate(numbers),使用 key 函数中的值进行比较

【讨论】:

    【解决方案2】:

    试试这个:

    ind = numbers.index(max(numbers))
    

    【讨论】:

    • 如果最大值出现多次怎么办?
    • @aj8uppal 我认为 OP 需要回答这个问题。
    【解决方案3】:
    def main():
       numbers = eval(input("Give me an array of numbers: "))
       indices = [i for i, x in enumerate(my_list) if x == max(numbers)]
       return indices
    

    运行方式:

    >>> indices = main()
    Give me an array of numbers: [1, 5, 9, 3, 2, 9]
    >>> indices
    [2, 5]
    

    此代码使用列表推导循环遍历列表并查看最大值在哪里使用max()。这也解释了可能存在不止一个最大值的事实,例如[1, 5, 9, 3, 2, 9]9 出现两次。

    【讨论】:

      猜你喜欢
      • 2018-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-25
      • 2016-08-21
      • 2014-05-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多