列表中值范围内的最小值

时间:2018-10-30 15:22:31

标签: python python-3.x list

我在python中有一个列表,它实际上是一个列表列表。我想在该列表的值范围内找到最小值(即局部最小值)。现在,我的代码看起来像

import numpy as np
import matplotlib.pyplot as plt
import os
import pylab as pyl

# create an array from the .txt file. Skip the number of headers of the table so you are left with only numbers in data.
#also each new cross section begins with the line ZONE, comment that out so you are only left wih data points in the array

data = np.genfromtxt('drip2cam1top.txt',comments='ZONE',skip_header=3)


print(data)

print(len(data))
# Generate two vectors x and h from the file. Reshape based on zone I and len(data)/I 
#(size of array,#number of points in a line) and then create two vectors
#divide len(data) by I to get first component and then use I (1808 in this case) for second component. #frames, I
x = np.reshape(data[:,0], [144,1808])
h = np.reshape(data[:,2], [144,1808])

#convert numpy array to a list
h_new = h.tolist()[::10] #every 10th step
x_new = x.tolist()[::10]

#using a trick called list comprehension in the next 4 statements,
#it's for constucting an array in one line
#You can look it up or just ignore it and use the results =)

#position of minima (column)
min_columns = [row.index(min(row)) for row in h_new] #position


#position of minima (row) #of frames is range
min_rows = list(range(144))[::10] #simply every row contains a minimum

#x coordinates of minima
min_coords = [x_new[0][index] for index in min_columns] 

#values of minima
min_values = [min(row) for row in h_new ] 


print(min_values)
print(min_columns)
print(min_rows)
print(min_coords)

#Uncomment the lines below to see the plot
#note the .T in the parameters, it transposes the matrices
#xlim and ylim are chosen based on the data. these can be commented out initially.
plt.xlim([-170,-162])
plt.ylim([-5.0,-4.2])
plt.plot(x[::10].T,h[::10].T)
plt.xlabel('x position (mm)')
plt.ylabel('Surface Height (mm)')
plt.plot(min_coords,min_values, 'ro', ms=3)
plt.title('Horizontal Cross Section of Analog Drip Model ')
plt.show()

这给了我每一行或“列表”中的最小值。我想在每行中找到-172和-162之间的最小值。

谢谢!

1 个答案:

答案 0 :(得分:4)

您可以通过生成器表达式有条件地计算min

min_values = [min(i for i in row if -172 <= i <= -162) for row in h_new]

当行中没有范围内的值时,您可能希望提供一个default参数:

min_values = [min((i for i in row if -172 <= i <= -162), default=0) for row in h_new]