假设我在 Python 中有一个由列表嵌套表示的 n 维矩阵。我想能够使用 n 元组来索引矩阵。这种操作是否可行?如何实现?
谢谢!
谢谢!
使用
>>> 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
以下是一种方法:
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
在 "def" 行中,你可以直接使用 1, 2
调用,即 print LookupByTuple(1, 2)
。其作用是将传入的参数打包成一个元组(tuple),并在函数内部解包使用。 - H.D.为了娱乐:
>>> 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
>>> 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
是矩阵实例,您可以使用minstance [0, 1, 2]
。 Numpy的ndarray
已经有类似的功能,但允许切片和赋值。indices = (12, 500, 60, 54)
val = matrixes[indices[0]][indices[1]][indices[2]][indices[3]]