Python 查找数组中最大值的索引

Python 查找数组中最大值的索引,python,Python,如何定位用户输入的数组中最大值的索引?以下是我所拥有的: def main(): numbers = eval(input("Give me an array of numbers: ")) largest = numbers[0] 试试这个: ind = numbers.index(max(numbers)) 这是: 枚举(数字)生成(索引、值)对 lambda pair:pair[1]获取这样一对并返回其值部分 max()返回max pair out枚举(数字),使用key

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

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

ind = numbers.index(max(numbers))
这是:

  • 枚举(数字)生成(索引、值)对
  • lambda pair:pair[1]获取这样一对并返回其值部分
  • max()返回max pair out枚举(数字),使用key函数中的值进行比较
运行方式为:

>>> 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
出现两次。

@ajm475du他想要索引,排序将更改所述索引。我真的很喜欢这种尝试。我不想因为使用
排序
的想法而获得“信任”。这是由于之前的一位评论者明智地删除了该评论。然而,我确实在应用它方面做得很糟糕。哈。如果最大值多次出现怎么办?@aj8uppal我想OP需要回答这个问题。
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]