I have an array
arr = [[[1, 2], [3, 4]], [5, 6]].
I am looking for a function f that returns me the indexes of the elements also in the nested array given only
arr as input.
function(arr, 2) -> (0, 0, 1)
Has some library implemented it?
Of course it’s not a problem if the array is a numpy array.
For this you dont necessarely need a special library, you can use the
numpy where function, like this:
import numpy as np def find_indices(arr, x): indices = np.where(np.array(arr) == x) return tuple(indices) # example usage arr = [[[1, 2], [3, 4]], [5, 6]] print(find_indices(arr, 2)) # output: (0, 0, 1)
edit: my code seem to fail on some case with the error
ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 2 dimensions. The detected shape was (2, 2) + inhomogeneous part.
here is a version that work without
def find_indices(arr, value): for i, sublist in enumerate(arr): for j, subsublist in enumerate(sublist): for k, item in enumerate(subsublist): if item == value: return i, j, k return None arr = [[[1, 2], [3, 4]], [5, 6]] print(find_indices(arr, 2)) # Output: (0, 0, 1)