[英]Large list, find all minima of list (python)
Given a large list of fluctuating values, how do you determine all local min values?给定大量波动值,您如何确定所有局部最小值? Not using numpy .不使用numpy 。 Local minimum means all values in a list that are the troughs of a function.局部最小值是指列表中作为函数波谷的所有值。
List_y = [23, 8, -7, 57, 87, 6]
I would like:我想:
New_list = [-7, 6]
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]
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]
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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.