def smallest_k(matrix: np.ndarray, k: int,
only_first_row: bool = False) -> Tuple[Tuple[np.ndarray, np.ndarray], np.ndarray]:
"""
Find the smallest elements in a numpy matrix.
:param matrix: Any matrix.
:param k: The number of smallest elements to return.
:param only_first_row: If true the search is constrained to the first row of the matrix.
:return: The row indices, column indices and values of the k smallest items in matrix.
"""
if only_first_row:
flatten = matrix[:1, :].flatten()
else:
flatten = matrix.flatten()
# args are the indices in flatten of the k smallest elements
args = np.argpartition(flatten, k)[:k]
# args are the indices in flatten of the sorted k smallest elements
args = args[np.argsort(flatten[args])]
# flatten[args] are the values for args
return np.unravel_index(args, matrix.shape), flatten[args]
评论列表
文章目录