Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Finding indexes of elements in nested arrays

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.

For example, function(arr, 2) -> (0, 0, 1)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Has some library implemented it?

Of course it’s not a problem if the array is a numpy array.

>Solution :

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[0])

# 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 numpy

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading