Large list, find all minima of list (python)

前端 未结 3 1703
无人共我
无人共我 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]
    

提交回复
热议问题