8

Assume I have an n-dimensional matrix in Python represented as lists of lists. I want to be able to use an n-tuple to index into the matrix. Is this possible? How?

Thank you!

2
  • 1
    if you're thinking of it as a matrix, you may(probably) want to be using numpy. Commented Aug 14, 2013 at 13:42
  • @roippi: you're right, i do Commented Aug 14, 2013 at 13:59

5 Answers 5

10

Using

>>> matrix = [[1, 2, 3], [4, 5, 6]]

You can do:

>>> array_ = numpy.asarray(matrix)
>>> array_[(1,2)]
6

Or without numpy:

>>> position = (1,2)
>>> matrix[position[0]][position[1]]
6
Sign up to request clarification or add additional context in comments.

1 Comment

numpy is really the way to go when dealing with matrices.
4

Here is one way:

matrx = [ [1,2,3], [4,5,6] ]

def LookupByTuple(tupl):
    answer = matrx
    for i in tupl:
        answer = answer[i]
    return answer

print LookupByTuple( (1,2) )

1 Comment

using *tupl in the "def" line you can call with 1, 2 directly, i.e., print LookupByTuple(1, 2)
3

For fun:

>>> get = lambda i,m: m if not i else get(i[1:], m[i[0]])

>>> matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> idx = (1,2)
>>> get(idx, matrix)
6

Comments

2

Yes

>>> from functools import reduce # Needed in Python 3
>>>
>>> # A 3D matrix
>>> m = [
...       [
...         [1, 2, 3],
...         [4, 5, 6]
...       ],
...       [
...         [-1, -2, -3],
...         [-4, -5, -6]
...       ]
...     ]
>>>
>>> m[0][1][2]
6
>>> tuple_idx = (0, 1, 2)
>>> reduce(lambda mat, idx: mat[idx], tuple_idx, m)
6

Or you can create a class Matrix in which you have a __getitem__ method (assuming the lists of lists is inside self.data):

class Matrix(object):
    # ... many other things here ...
    def __getitem__(self, *args):
        return reduce(lambda mat, idx: mat[idx], args, self.data)

With that method you can use minstance[0, 1, 2] if minstance is a Matrix instance.

Numpy ndarray already has something like that, but allowing slices and assignments.

Comments

0

If your code guarantees that each index in the tuple corresponds to a different "level" of the matrix, then you can just index each sublist directly.

indices = (12, 500, 60, 54)
val =  matrixes[indices[0]][indices[1]][indices[2]][indices[3]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.