NXN矩阵的所有对角元素,不使用python中的numpy

时间:2013-12-20 05:32:20

标签: python algorithm matrix

尝试在不使用numpy的情况下获取NXN矩阵的所有对角元素,

这与Get diagonal without using numpy in Python

不同

请不要标记为重复。

这是我使用两次迭代的片段,它将打印从(0,0)到(n,n)的所有对角线元素。有人可以帮助我改进我的迭代过程或任何递归方式。

#!/usr/bin/python 

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

def get_matrix_diagonal(m): 
    col = len(m) 
    result = list() 
    row = 0 
    for c in range(col): 
        position = list() 
        position.append([row,c]) 
        if c > 0: 
            i = c 
            while i > 0: 
                x = i - 1 
                y = c - i + 1 
                position.append([y,x]) 
                i -= 1 
        result.append(position) 
    row = row + 1 
    cc = c 
    for i in range(row,col): 
        position = list() 
        y = i 
        x = c 
        position.append([y,x]) 
        j = x - y 
        while j > 0: 
            y = c - j + 1 
            x = cc - y + 1 
            position.append([y,x]) 
            j -= 1 
        cc += 1
        result.append(position)
    return result

for ls in get_matrix_diagonal(matrix):
    for co in ls:
        x,y = co[0],co[1],
        print matrix[x][y],
    print

输出:

1
2 2
3 3 3
4 4 4 4
5 5 5
6 6
7

2 个答案:

答案 0 :(得分:4)

>>> matrix = [[1,2,3,4], 
...           [2,3,4,5], 
...           [3,4,5,6], 
...           [4,5,6,7]] 
>>> N = 4
>>> [[matrix[y-x][x] for x in range(N) if 0<=y-x<N] for y in range(2*N-1)]
[[1], [2, 2], [3, 3, 3], [4, 4, 4, 4], [5, 5, 5], [6, 6], [7]]

答案 1 :(得分:1)

这里假设矩阵是正方形的递归方法:

def diagonals(m):
    if len(m) == 1: return m
    d = [[]] + diagonals([r[1:] for r in m[:-1]]) + [[]]
    r = [r[0] for r in m] + m[-1][1:]
    return [[r] + d for r, d in zip(r,d)]