1

I would like the simplest way to an element of a multidimensional array in Python from a tuple/list of the indexes.

I.e. f( M, (a,b,c) ) returns M[a][b][c]

Is there a straightforward way to get this without coding it myself?

7
  • Can you give some concrete input and output examples Commented Jun 19, 2019 at 20:31
  • Is your M a list of lists? Did you consider if numpy.array would be more suitable for your need? Commented Jun 19, 2019 at 20:36
  • @ImperishableNight: Yes, M is a list of lists (or tuples) Commented Jun 19, 2019 at 21:03
  • @ImperishableNight: What changes if it's a numpy.array ? Commented Jun 19, 2019 at 21:04
  • what can be better than what you wrote? M[a][b][c].... Commented Jun 19, 2019 at 21:12

1 Answer 1

0

You can use numpy arrays for that.

Example:

import numpy as np
x = [ [[1,1,1],[1,1,1], [1,1,1]], [[2,2,2],[2,2,2],[2,2,2]], [[3,3,3], [3,3,3], [3,3,3]]]
matrix = np.array(x)
print(matrix[0,0,0]) # prints first element in matrix
Sign up to request clarification or add additional context in comments.

2 Comments

Wait, that syntax can't be right, right? Do you mean matrix[(0,0,0)] ?
Both work. You can also use matrix[(0,0,0)]. Just copy the script and test it on python terminal. Remember to install numpy via pip install numpy

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.