Define list within matrix

1

I would like to be able to create a variable that was an N x N matrix and that each of the positions in the matrix would be a list of two elements.

and be able to assign them in a similar way to this, within a for loop:

matriz[1][2]=[345.545, 415.213]

How do I define the variable matrix? I've tried something like:

matriz = np.array(N,N), dtype=list)

but it does not work well.

    
asked by Juanca M 10.04.2017 в 15:46
source

2 answers

2

If you want to access a list or a array with the operator [][] , you just have to put a list within another list, in Python 2 and 3 you can do it in the same way:

# Suponiendo que N sean 10 items:
N = 10
# Creamos la lista de NxN listas.
matriz = list([ list([]) for i in range(0, N) ] for k in range(0, N)) 
matriz[1][2] = [ 345.545, 415.213 ]
print(matriz) # imprime la lista.

You should print:

[
    [[], [], [], [], [], [], [], [], [], []], 
    [[], [], [345.545, 415.213], [], [], [], [], [], [], []], 
    [[], [], [], [], [], [], [], [], [], []], 
    [[], [], [], [], [], [], [], [], [], []], 
    [[], [], [], [], [], [], [], [], [], []], 
    [[], [], [], [], [], [], [], [], [], []], 
    [[], [], [], [], [], [], [], [], [], []], 
    [[], [], [], [], [], [], [], [], [], []], 
    [[], [], [], [], [], [], [], [], [], []], 
    [[], [], [], [], [], [], [], [], [], []]
]
    
answered by 10.04.2017 / 16:38
source
1

If I have not confused what you want is a three-dimensional array, that is, an NxN matrix where each element is an array / list of one dimension with two elements. Since you work with NumPy you should use a np.array and not a list for each element of the matrix. You can start your matrix with all the elements to 0 using numpy.zeros :

>>> import numpy as np
>>> N = 3
>>> matriz = np.zeros((N,N,2))
>>> matriz[1][2]=[345.545, 415.213]
>>> matriz
array([[[   0.   ,    0.   ],
        [   0.   ,    0.   ],
        [   0.   ,    0.   ]],

       [[   0.   ,    0.   ],
        [   0.   ,    0.   ],
        [ 345.545,  415.213]],

       [[   0.   ,    0.   ],
        [   0.   ,    0.   ],
        [   0.   ,    0.   ]]])
    
answered by 10.04.2017 в 16:56