Python Forum

Full Version: Function to return list of all the INDEX values of a defined ndarray?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
If I have a numpy.ndarray defined as follows:

import numpy as np
x = np.ndarray([2,2,2], order='C', dtype='<U3')
Is there a function to return all the valid INDEX values for that array? I would hope to see a set of values like the following:

Output:
[[0,0,0], [0,0,1], [0,1,0], [0,1,1], [1,0,0], [1,0,1], [1,1,0], [1,1,1]]
Is that possible?

Peter
Could grab the dimension via np.shape() and then iterate over them with itertools.product()

import numpy as np
from itertools import product
x = np.ndarray([2,2,2], order='C', dtype='<U3')
print(list(product(*map(lambda x: range(x), np.shape(x))))
Output:
[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]
Nice. Thanks, that seems to solve my problem.

Peter