我有一个由 N
个子列表组成的嵌套列表 a
,每个子列表都填充有 M
float 。我有办法使用 numpy 获取最大 float 的索引,如下面的 MWE 所示:
import numpy as np
def random_data(bot, top, N):
# Generate some random data.
return np.random.uniform(bot, top, N)
# Generate nested list a.
N, M = 10, 7 # number of sublists and length of each sublist
a = np.asarray([random_data(0., 1., M) for _ in range(N)])
# x,y indexes of max float in a.
print np.unravel_index(a.argmax(), a.shape)
请注意,我使用子列表索引和浮点索引作为 x,y
坐标,其中 x
是子列表的索引,y
code> 所述子列表内的 float 索引。
我现在需要的是一种找到施加某些边界的最大 float 的坐标/索引的方法。例如,我想获取 x
和 中
在 [3:5]
范围内最大 float 的 x,y
值>[2:6]y
中。
这意味着我想搜索 a
内最大的 float ,但将该搜索限制为 [3:5]
内的那些子列表,并且在这些子列表中将其限制为漂浮在[2:6]
内。
我可以使用:
print np.unravel_index(a[3:5].argmax(), a[3:5].shape)
限制x
中的范围,但返回的索引移动了,因为列表被切片,而且我想不出有什么办法来获取y
以这种方式索引。
最佳答案
另一种解决方案是将范围之外的值设置为np.inf
:
import numpy as np
# Generate nested list a.
N, M = 10, 7 # number of sublists and length of each sublist
a = np.random.rand(N, M)
# x,y indexes of max float in a.
print np.unravel_index(a.argmax(), a.shape)
A = np.full_like(a, -np.inf) # use np.inf if doing np.argmin
A[3:5, 2:6] = a[3:5, 2:6]
np.unravel_index(A.argmax(), A.shape)
关于python - 获取嵌套列表中最大值的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22825209/