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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20447210/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:27:46  来源:igfitidea点击:

Get diagonal without using numpy?

pythonmatrix

提问by user3078618

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?

我正在尝试从 Python 中的矩阵中获取对角线而不使用numpy(我真的无法使用它)。这里有人知道怎么做吗?

Example of what I want to get:

我想得到的例子:

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

Or like:

或者像:

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

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

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

采纳答案by jez

To get the leading diagonal you could do

要获得领先的对角线,您可以这样做

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

or even

甚至

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) ]

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

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

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

回答by bcorso

def get_diagonal(m, i0, j0, d):
    return [m[(i0 + i - 1)%len(m)][(j0 + d*i - 1)%len(m[0])]
                for i in range(len(m))]

Which gets the diagonals in forward or reverse directions:

得到正向或反向对角线:

m = [[1, 2, 3, 4],
     [5, 6, 7, 8],
     [9,10,11,12]]

print get_diagonal(m, 1, 1, 1)    # [1, 6, 11]
print get_diagonal(m, 1, 2, 1)    # [2, 7, 12]
print get_diagonal(m, 1, 4,-1)    # [4, 7, 10]

It even wraps around the matrix to get diagonals:

它甚至环绕矩阵以获得对角线:

print get_diagonal(m, 1, 4, 1)    # [4, 5, 10]
print get_diagonal(m, 1, 1,-1)    # [1, 8, 11]
print get_diagonal(m, 3, 1, 1)    # [9, 2, 7 ]

回答by Shoaib Ali C H

Well, I have a solution that works for me.

好吧,我有一个适合我的解决方案。

Input :

输入 :

First line contains an integer N

第一行包含一个整数 N

The next N lines denote the matrix's rows, with each line containing space-separated integers describing the columns.

接下来的 N 行表示矩阵的行,每行包含描述列的空格分隔的整数。

Sample Input :

样本输入:

3
11 2 4
4 5 6
10 8 -12

Code :

代码 :

import sys


n = int(input().strip())
a = []
for a_i in range(n):
    a_t = [int(a_temp) for a_temp in input().strip().split(' ')]
    a.append(a_t)

pri_d = [];
pri_m = 0;
sec_d = [];
sec_m = n - 1;
for i in a:
    pri_d.append(i[pri_m]);
    sec_d.append(i[sec_m]);
    pri_m = pri_m + 1;
    sec_m = sec_m - 1;
print(pri_d);
print(sec_d);

output :

输出 :

[11, 5, -12]
[4, 5, 10]

回答by Lean Bravo

Since nobody mentioned map or lambdas here, I'll leave a solution:

由于这里没有人提到 map 或 lambdas,我将留下一个解决方案:

list(map(lambda x: x[a.index(x)], a))

That way at array 0 it will grab element 0, and so on.

这样在数组 0 处,它将抓取元素 0,依此类推。

As for the opposite diagonal you might want to either flip the array bottom-up or take into consideration the length of the array minus one and subtract the current index to it:

至于相反的对角线,您可能想要自下而上翻转数组,或者考虑数组的长度减去一并减去当前索引:

list(map(lambda x: x[(len(a) - 1) - a.index(x)], a)))

Hope it helps!

希望能帮助到你!

回答by Rodrigo Carneiro

For diagonal:

对于对角线:

[m[i][i] for i in xrange(0, len(m))]

[m[i][i] for i in xrange(0, len(m))]

For counter-diagonal:

对于对角线:

[m[i][~i] for i in xrange(0, len(m))]

[m[i][~i] for i in xrange(0, len(m))]