快速获取下三角矩阵的索引作为python中的一维列表

pac*_*erg 3 python numpy matrix triangular

给定方形矩阵的行(或列)数n,我试图得到一维列表中下三角矩阵的索引对.到目前为止,我想到了以下解决方案:

def getLowerTriangularIndices(n):
    inds=[];         
    for i in range(1,n):
        for j in range(i):
            inds.append((i,j))
    return inds;
Run Code Online (Sandbox Code Playgroud)

考虑到两个for循环,使用numpy有一个更有效的计算方法会好得多.有没有人有建议?

Tho*_*anz 6

Numpy有一个方法...

import numpy as np

# create your matrix. If it's not yet a numpy array, make it one
ar = np.array(matrix)
indices = np.tril_indices_from(ar)
Run Code Online (Sandbox Code Playgroud)

这将返回两个数组的元组.如果你想将它们作为列表,你可以这样做

indices = [list(x) for x in np.tril_indices_from(ar)]
Run Code Online (Sandbox Code Playgroud)

实际上你不需要有一个数组来获取索引,还有np.tril_indices,它将形状作为参数.

所以你的功能如下:

def getLowerTriangularIndices(n):
    return [list(x) for x in np.tril_indices(n)]
Run Code Online (Sandbox Code Playgroud)

或者如果你想要一个元组列表:

def getLowerTriangularIndices(n):
    return zip(*np.tril_indices(n)]
Run Code Online (Sandbox Code Playgroud)