Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
456 views
in Technique[技术] by (71.8m points)

python - Get diagonal without using numpy?

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?

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==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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 if conditionals in the list comprehension, e.g.:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...