本文介绍了在不使用numpy的情况下获得对角线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在不使用numpy的情况下从Python矩阵中获取对角线(我真的不能使用它).这里有人知道怎么做吗?

I'm trying to get the diagonal from a matrix in Python without using numpy (I really can't use it). Does someone here knows how to do it?

我想要得到的例子:

get_diagonal ([[1,2,3,4],[5,6,7,8],[9,10,11,12]], 1, 1, 1)
Result: [1, 6, 11]

或类似:

get_diagonal ([[1,2,3,4],[5,6,7,8],[9,10,11,12]], 1, 2, 1)
Result: [2, 7, 12]

直到知道我已经尝试了很多东西但没有用.

Until know I've tried a lot of stuff but doesn't work.

def obter_diagonal(matrix, line, column, direc):
    d = []
    if direc == 1:
        for i in matrix:
            for j in i:
                if all(i == line, j == column):
                    d.extend(matrix[i][j])
    else:
        for i in matrix:
            for j in i:
                d.extend[len(matrix)-1-i][j]
    return d

如果direc==1我需要获取从左->右,上->下的对角线.
如果direc==-1需要获取从右->左,上->下的诊断.

If direc==1 I need to get the diagonal that goes from left-> right, top-> bottom.
If direc==-1 need to get the diag that goes from right-> left, top->bottom.

推荐答案

要获得对角线,您可以做到

To get the leading diagonal you could do

diag = [ mat[i][i] for i in range(len(mat)) ]

甚至

diag = [ row[i] for i,row in enumerate(mat) ]

并为其他对角线玩类似的游戏.例如,对于反对角线(从右上到左下),您可以执行以下操作:

And play similar games for other diagonals. For example, for the counter-diagonal (top-right to bottom-left) you would do something like:

diag = [ row[-i-1] for i,row in enumerate(mat) ]

对于其他次要对角线,您必须在列表理解中使用if条件,例如:

For other minor diagonals you would have to use if conditionals in the list comprehension, e.g.:

diag = [ row[i+offset] for i,row in enumerate(mat) if 0 <= i+offset < len(row)]

这篇关于在不使用numpy的情况下获得对角线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 16:51