python - 列表中某个值范围内的最小值
问题描述
我在 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 值之间的最小值。
谢谢!
解决方案
您可以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]
推荐阅读
- python-3.x - 引用顶级模块python
- robotframework - 如何在机器人框架的套件设置中获取当前的测试用例名称?
- python - 向 Pandas 数据框中添加一列,其中 A、B、C 重复
- haskell - 如何为给定数据类型的 Show 编写更短的实例?
- android - 在 Dispatcher.Main 的上下文中执行网络任务
- php - 如何在 Symfony 中正确使用自定义类型?
- firebase - Flutter / Firebase在null上调用了getter'length'
- sql-server - SQL Server varchar(max) 无法正常工作
- wcf - 使用 WcfCoreMtomEncoder 记录响应 XML?
- ios - 在 Swift 中对来自 firestore 的数组进行分组