不使用numpy的矩阵中所有对角线的列表-Python 3

时间:2019-04-23 12:48:21

标签: python-3.x matrix

假设我得到以下矩阵:

[[5,4,3,2], [8,7,6,5], [4,3,2,0]]

我想创建2个单独的函数,这些函数创建一个从右到左以及从左到右的所有对角线列表,而不使用numpy模块!

对于e.x:

[[4], [8,3], [5,7,2], [4,6,0], [3,5], [2]]   # these are the right to left diagonals

我尝试了几种不同的方法,但是都没有成功。另外,我相当仔细地扫描了堆栈溢出以寻找答案,但是没有找到不包含numpy的任何内容。

编辑:这是我编写的用于处理某些对角线的代码:

L = [[5, 4, 3, 2], [8, 7, 6, 5], [4, 3, 2, 0]]


def search_diagonally_rtl(matrix):
    num_of_rows = len(matrix)
    num_of_cols = len(matrix[0])
    diag_mat = list()
    for i in range(0, num_of_rows):
        diag_mat.append([matrix[i][0]])
    row_index = 0
    for row in diag_mat:
        for k in range(0, row_index):
            i = k
            j = 1
            while i >= 0:
                row.append(matrix[i][j])
                i = i - 1
                j = j + 1
        row_index += 1

输出为:[[5], [8, 4], [4, 4, 7, 3]]

但应为:[[5], [8, 4], [4, 7, 3]]

1 个答案:

答案 0 :(得分:0)

def diag1(x, startline):
    out = []
    line = startline
    col = 0
    while line < len(x) and col < len(x[0]):
        out.append(x[line][col])
        line +=1
        col += 1
    return out


def diag2(x, startcol):
    out = []
    line = 0
    col = startcol
    while line < len(x) and col < len(x[0]):
        out.append(x[line][col])
        line +=1
        col += 1
    return out


def diag(x):
    out = []
    for startline in range(len(x) - 1, -1, -1):
        out.append(diag1(x, startline))
    for startcol in range(1, len(x[0])):
        out.append(diag2(x, startcol))
    return out


x = [[5,4,3,2], [8,7,6,5], [4,3,2,0]]
print(diag(x))  # [[4], [8, 3], [5, 7, 2], [4, 6, 0], [3, 5], [2]]

diag1从矩阵的左边界开始并返回对角线,而diag2从矩阵的左边界开始。 diag结合了两种方法。
对其他方向上的对角线几乎不需要适应。