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!
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!
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
numpy is really the way to go when dealing with matrices.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) )
*tupl in the "def" line you can call with 1, 2 directly, i.e., print LookupByTuple(1, 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.