How to transform a diagonal elements list from a python array [closed]

0

I have the following array, for example:

         1 2 3 4 5 6
         7 8 9 3 8 9
matriz = 4 5 2 3 4 4
         2 3 4 5 3 6
         4 5 3 4 5 6

I would like to get only the elements of the main diagonal, such as:

A = [1, 8, 2, 5, 5]
    
asked by anonymous 07.12.2017 / 13:08

1 answer

4

Your question really is not very clear. If your array is a list of lists, the solution is as follows:

matriz = [[1, 2, 3, 4, 5, 6],
           [7, 8, 9, 3, 8, 9],
           [4, 5, 2, 3, 4, 4],
           [2, 3, 4, 5, 3, 6],
           [4, 5, 3, 4, 5, 6]]

diag = []
for i in range(len(matriz)):
    for j in range(len(matriz[0])):
        if i == j:
            diag.append(matriz[i][j])

print(diag)

Output is [1, 8, 2, 5, 5]

Whether your array is an array numpy (and if not, I I recommend using this library) the solution is as follows:

import numpy as np
array = np.array(matriz)
np.diag(array)

And the output is array([1, 8, 2, 5, 5])

    
07.12.2017 / 15:17