对角线与方形矩阵中的第一对角线平行

时间:2017-01-12 13:05:19

标签: python-3.x

我希望使用python获得与方形矩阵中第一个对角线平行的所有对角线。

    matrix = [[1,2,3,4],
              [5,6,7,8],
              [9,0,1,2],
              [3,4,5,6]]

    for i in range(len(matrix)):
       for j in range(len(matrix)):
           diagonal = []
           if i == j + 1 :
                diagonal.append(mat[i][j])
                print(diagonal, end=" ")

用我的第一个对角线:

    [1][6][1][6]

输出是:

    [5] [0] [5]

但我正在寻找他们两个:

    [5] [0] [5] and 
    [9] [4]

1 个答案:

答案 0 :(得分:0)

如果您安装了numpy,则免费获得diagonals (with offsets)

import numpy as np

matrix = np.array( [[1,2,3,4],
              [5,6,7,8],
              [9,0,1,2],
              [3,4,5,6]])

print(matrix.diagonal())          # -> [1 6 1 6]
print(matrix.diagonal(offset=-1)) # -> [5 0 5]
print(matrix.diagonal(offset=-2)) # -> [9 4]

这是一种手动执行此操作的方法:

def diagonal(matrix, offset=0):
    ret = []
    l = len(matrix)
    for i, row in enumerate(matrix):
        j = i+offset
        if j < 0:
            continue
        if j >= l:
            break
        ret.append(row[j])
    return ret

print(diagonal(matrix))            # -> [1, 6, 1, 6]
print(diagonal(matrix, offset=-1)) # -> [5, 0, 5]
print(diagonal(matrix, offset=-2)) # -> [9, 4]

或更紧凑高效的版本,使用列表理解生成对角线:

def diagonal(matrix, offset=0):
    dim = len(matrix)
    return [matrix[i][j] for i, j in
            zip(range(-offset if offset < 0 else 0, dim),
                range(offset if offset > 0 else 0, dim))]