Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract the anti-diagonal of a 2D list

Tags:

python

list

I am trying to print the diagonal numbers of this matrix so that I get [5, 9, 13, 17, 21].

I've tried changing the variables in the for loop.

matrix = [[ 1,  2,  3,  4,  5],
          [ 6,  7,  8,  9, 10],
          [11, 12, 13, 14, 15],
          [16, 17, 18, 19, 20],
          [21, 22, 23, 24, 25]]

diagonal = []
last_column = len(matrix[0]) - 1
for row in matrix:
    diagonal.append([row][0][4])

print(diagonal)

Instead of getting the diagonal numbers, I get [5, 10, 15, 20, 25].

like image 859
Jason7261 Avatar asked Mar 04 '23 05:03

Jason7261


2 Answers

You can also use numpy.diagonal

import numpy
matrix = [[ 1,  2,  3,  4,  5],
          [ 6,  7,  8,  9, 10],
          [11, 12, 13, 14, 15],
          [16, 17, 18, 19, 20],
          [21, 22, 23, 24, 25]]
arr=numpy.array(matrix)
print(numpy.fliplr(arr).diagonal())

Outputs:

[ 5  9 13 17 21]

To get the diagonal use print(arr.diagonal())

like image 176
Bitto Bennichan Avatar answered Mar 16 '23 10:03

Bitto Bennichan


You want the anti-diagonal, so you can use a simple list comprehension (assuming matrix is square).

[matrix[i][-(i+1)] for i in range(len(matrix))]
# [5, 9, 13, 17, 21]
like image 29
cs95 Avatar answered Mar 16 '23 09:03

cs95