在不使用numpy的情况下获得对角线?

编程入门 行业动态 更新时间:2024-10-28 12:24:48
本文介绍了在不使用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的情况下获得对角线?

本文发布于:2023-11-30 10:22:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649638.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对角线   情况下   numpy

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!