我有'n‘个列表序列,我发送给绘图例程。每个列表中的第二个元素是用于绘制x轴的频率断点。我需要遍历“n”系列中的每一个,并找出绝对最低频率断点是什么,而wat是在曲线图上建立X轴边界的绝对最高频率断点。
每个列表由任意数量的列表组成:[‘传感器描述’,频率断点,这些断点处的幅度],即:[[‘传感器_A’,0.1,1.0,10.0,1.5,15.0,150.0],[‘传感器_B’,0.05,1.0,20.0,0.5,15.0,300.0]]
我以为我可以直接用numpy.amax和numpy.amin来做这件事,但还没有找到正确的组合……我是否必须一次只迭代一个元素,或者我可以使用a来获取amax,amin函数来为我做这件事?
还没有找到更好的解决方案,但似乎有一种更快的方法。
pc = [['sensor_A',[0.05,1.0,10.0],[1.5,15.0,150.0]],['sensor_B',[0.2,1.0,20.0],[0.5,15.0,300.0]]]
# I want the nmax of the second list from each of the lists, which should be 20
# I want the nmin of the second list from each of the lists, which should be 0.05
print(np.amax(pc[1][1])) # unfortunately this only looks at the second list
print(np.amin(pc[1][1])) # and ignores the first.
max=0 # This works but seems kind of clunky. Is there a shorter solution?
min=1.0E+6
for p in pc:
if (np.amax(p[1]) > max):
max = np.amax(p[1])
if (np.amin(p[1]) < min):
min = np.amin(p[1])
print( min,max )
发布于 2019-05-15 22:34:19
我不认为您可以使用numpy
来完成此任务,因为您的输入列表不是numpy数组。您必须使用内置的min
和max
函数。
pc = [['sensor_A',[0.05,1.0,10.0],[1.5,15.0,150.0]],['sensor_B',[0.2,1.0,20.0],[0.5,15.0,300.0]]]
# the builtin max function can accept a key to use when determining the max.
# Since you want the max from the 2nd list in each element in pc, we can use
max_item = max(pc, key = lambda i: max(i[1]))
# The lambda creates an anonymous function that takes in one argument, i,
# which is each outer list in pc and then uses the maximum of the 2nd element
# (which is your freq breakpoints) to determine the final maximum. The output
# will be an outer-list from pc.
print(max_item)
# outputs: >> ['sensor_B', [0.2, 1.0, 20.0], [0.5, 15.0, 300.0]]
# We get the right output, we know 20 is the max freq breakpoint from our eyes...
# Now we have the element in pc that has the max freq breakpoint, pull out the max
xmax = max(max_item[1])
# max_item[1] is the list of freq breakpoints, and we just take the max from that.
# It can be confusing with so many max's, so let's put it all together on one line.
xmax_oneline = max(max(pc, key = lambda i: max(i[1]))[1])
print(xmax_oneline)
# Outputs: >> 20.0 as desired.
# We can do similar to find the minimum
xmin_oneline = min(min(pc, key = lambda i: min(i[1]))[1])
print(xmin_oneline)
# Outputs: >> 0.05 as desired.
https://stackoverflow.com/questions/56155770
复制相似问题