2 回答
TA贡献1827条经验 获得超8个赞
和
numpy.argpartition,numpy.unravel_index和numpy.column_stack套路:
测试ndarrayarr是改组数组值0到99形状的(11, 9)。
假设我们要查找前7个最大值的2d索引列表:
In [1018]: arr
Out[1018]:
array([[36, 37, 38, 39, 40, 41, 42, 43, 44],
[27, 28, 29, 30, 31, 32, 33, 34, 35],
[72, 73, 74, 75, 76, 77, 78, 79, 80],
[ 0, 1, 2, 3, 4, 5, 6, 7, 8],
[18, 19, 20, 21, 22, 23, 24, 25, 26],
[45, 46, 47, 48, 49, 50, 51, 52, 53],
[ 9, 10, 11, 12, 13, 14, 15, 16, 17],
[90, 91, 92, 93, 94, 95, 96, 97, 98],
[54, 55, 56, 57, 58, 59, 60, 61, 62],
[63, 64, 65, 66, 67, 68, 69, 70, 71],
[81, 82, 83, 84, 85, 86, 87, 88, 89]])
In [1019]: top_N = 7
In [1020]: idx = np.argpartition(arr, arr.size - top_N, axis=None)[-top_N:]
In [1021]: result = np.column_stack(np.unravel_index(idx, arr.shape))
In [1022]: result
Out[1022]:
array([[7, 2],
[7, 3],
[7, 4],
[7, 5],
[7, 7],
[7, 8],
[7, 6]])
TA贡献1847条经验 获得超11个赞
这是我想到的解决方案,希望它可以足够快地满足您的需求。
num_list = [
[1.2, 9.5, 4.8, 1.7],
[5.5, 8.1, 7.6, 7.1],
[5.5, 9.6, 7.6, 7.1],
[5.5, 8.1, 4.5, 7.1],
[1.4, 6.9, 7.8, 12.2]
]
needed_highest = 5 # This is where your 100 would go
highest = [-1] * needed_highest
result = [-1] * needed_highest
for y in range(0, len(num_list)):
for x in range(0, len(num_list[y])):
num = num_list[y][x]
min_index = highest.index(min(highest))
min_value = highest[min_index]
if min_value < num:
highest[min_index] = num
result[min_index] = (x, y)
print(result)
结果没有以任何方式排序,但是如果需要的话,应该不难实现。
添加回答
举报