【问题标题】:how to find index of min and max value of a int array Python [duplicate]如何找到int数组Python的最小值和最大值的索引[重复]
【发布时间】:2018-10-22 05:01:49
【问题描述】:

您好,我想查找整数数组的最大值和最小值的第一个索引。

如果有重复值,我的代码会返回所有索引...

A= [1,1,8,7,5,9,6,9]
def minmaxloc(num_list):
  for i,y in enumerate(num_list):
    if y ==max(num_list) or y==min(num_list):
      print i
minmaxloc(A)

输出: 0 1 5 7

我想要什么: (0,5)

感谢您的帮助。

【问题讨论】:

  • import numpy as np; (np.argmin(A),np.argmax(A))
  • 您所指出的问题中的最佳答案并不是那么好,因为它可能会扫描阵列两次。第二个答案stackoverflow.com/a/2474238/500207 在这方面更好。理想情况下,您可以在一次扫描中计算最大值和最小值,但 Python 或 Numpy 都没有提供 minmax :(

标签: python max min enumerate


【解决方案1】:
def minmaxloc(num_list):
    return num_list.index(max(num_list)), num_list.index(min(num_list))

print(minmaxloc(a))

【讨论】:

    【解决方案2】:

    使用 numpy 的 argmin 和 argmax 方法:

    import numpy as np
    def minmaxloc(num_list):
        return np.argmin(num_list), np.argmax(num_list)
    A= [1,1,8,7,5,9,6,9]
    print(minmaxloc(A))
    

    【讨论】:

    • 感谢您的帮助!它工作正常但我想使用枚举
    • 为什么投反对票?你能详细说明为什么需要枚举吗?似乎还有更多的故事。
    猜你喜欢
    • 2019-08-21
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 2013-01-11
    • 1970-01-01
    • 2018-04-25
    • 2016-08-21
    • 2014-05-19
    相关资源
    最近更新 更多