Large list, find all minima of list (python)

前端 未结 3 1702
无人共我
无人共我 2021-01-07 17:02

Given a large list of fluctuating values, how do you determine all local min values? Not using numpy. Local minimum means all values in a list that are the troughs

相关标签:
3条回答
  • 2021-01-07 17:57

    I'm a big fan of iterating over these problems in stages.

    l = [23, 8, -7, -7, 57, 87, 6]
    
    # Remove identical neighbors
    # l becomes [23, 8, -7, 57, 87, 6]
    l = [x for x,y in zip(l[0:], l[1:]) if x != y] + [l[-1]]
    
    # Append positive infinity to both endpoints
    # l becomes [inf, 23, 8, -7, 57, 87, 6, inf]
    l = [float("inf")] + l + [float("inf")]
    
    # Retain elements where each of their neighbors are greater than them.
    # l becomes [-7, 6]
    l = [y for x, y, z in zip(l[0:], l[1:], l[2:]) if x > y < z]
    
    0 讨论(0)
  • 2021-01-07 18:02

    Here You can easily understand array sorting...

    my_array = [10,20,30,5,1,8,2,14,6,29] #main array
    if len(my_array) > 0:
        my_array.sort() #sorting array(min to max)
        min = my_array[0] #after sorting get min value
        print(min) #print min value
    else:
        print("array is empty")
    
    0 讨论(0)
  • 2021-01-07 18:03
    def local_min(ys):
        return [y for i, y in enumerate(ys)
                if ((i == 0) or (ys[i - 1] >= y))
                and ((i == len(ys) - 1) or (y < ys[i+1]))]
    
    
    >>> local_min([23, 8, -7, 57, 87, 6])
    [-7, 6]
    >>> local_min([23, 6, 6, 6, 42])
    [6]
    >>> local_min([6, 6, 4])
    [4]
    
    0 讨论(0)
提交回复
热议问题