如何找到用户输入的数组中最大值的索引?这就是我所拥有的:
def main():
numbers = eval(input("Give me an array of numbers: "))
largest = numbers[0]
答案 0 :(得分:1)
max_index, max_value = max(enumerate(numbers), key=lambda pair: pair[1])
这样做:
答案 1 :(得分:0)
试试这个:
ind = numbers.index(max(numbers))
答案 2 :(得分:0)
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
出现两次。