zoukankan      html  css  js  c++  java
  • python快速求一个数组的最大值/最小值及其索引

    enumerate()函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标。

    x = [3, 2.2, 7.4, 6, 4]
    list(enumerate(x))
    # 输出 [(0, 3), (1, 2.2), (2, 7.4), (3, 6), (4, 4)]

    operator.itemgetter()函数用于获取对象的哪些维的数据,参数为想要取的一些维度序号。

    x = [3, 2.2, 7.4, 6, 4]
    b1 = operator.itemgetter(2, 1)
    b1(x) # 输出 (7.4, 2.2)
     
    b2 = operator.itemgetter(3)
    b2(x) # 输出 6

    最后max()函数有一个应用很巧妙的参数key,在这里定义为operator.itemgetter(1),表示对enumerate(x)每个元素的第一维做比较(从0维开始),然后返回第一维值最大的元素,即包含索引和数值。

    x = [3, 2.2, 7.4, 6, 4]
    min_index, min_number = min(enumerate(x), key=operator.itemgetter(1))
    # min_index=1,  min_number =2.2
     
    max_index, max_number = max(enumerate(x), key=operator.itemgetter(1))
    # max_index=2,  max_number = 7.4
    

     还有另一个简单且low的方法,index()函数返回参数在数组中第一次出现的索引的值,如果数组中不含有这个参数,则抛出异常。

    num = [4,1,2,3,4]
    max = max(num)
    max_index = num.index(max)
    #max_index=0

    借鉴于:https://blog.csdn.net/qq_15056979/article/details/89194723

  • 相关阅读:
    SDOI2011古代朱文
    LIS 堆优化
    ZR2019 广州 游记
    LG2709 小B的询问
    [SCOI2009] 生日礼物
    [SDOI2008]沙拉公主的困惑
    [LG3396]哈希冲突
    ZROI2018.8.2 菜鸡互啄杯组队 ACM 赛
    ZROI 菜鸡互啄杯 III
    [LG4016] 负载平衡问题
  • 原文地址:https://www.cnblogs.com/123456www/p/12545794.html
Copyright © 2011-2022 走看看