4

假设我在 Python 中有一个 n 维矩阵,表示为列表列表。我希望能够使用 n 元组来索引矩阵。这可能吗?如何?

谢谢!

4

5 回答 5

8

使用

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

你可以做:

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

或者没有 numpy:

>>> position = (1,2)
>>> matrix[position[0]][position[1]]
6
于 2013-08-14T13:41:55.710 回答
4

这是一种方法:

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) )
于 2013-08-14T13:39:22.883 回答
3

为了娱乐:

>>> 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
于 2013-08-14T14:16:18.490 回答
2

是的

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

或者您可以创建一个类 Matrix,其中您有一个__getitem__方法(假设列表列表在 self.data 中):

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

使用该方法,您可以使用minstance[0, 1, 2]ifminstance是 Matrix 实例。

Numpy ndarray已经有类似的东西,但允许切片和分配。

于 2013-08-14T13:52:15.673 回答
0

如果您的代码保证元组中的每个索引对应于矩阵的不同“级别”,那么您可以直接索引每个子列表。

indices = (12, 500, 60, 54)
val =  matrixes[indices[0]][indices[1]][indices[2]][indices[3]]
于 2013-08-14T13:46:20.823 回答