How to generate a matrix with a list that contains data?

1

Cordial greeting.

I have a list of the following form.

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

and I want to generate a 4x3 matrix with that list and with that data, in such a  so I have something like this:

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

Thank you for your attention.

    
asked by Yeison Ordoñez 21.04.2016 в 21:51
source

2 answers

2

You can use numpy.reshape

>>> import numpy as np
>>> L=[1,2,3,4,5,6,7,8,9,10,11,12]
>>> np.array(L).reshape(4,3)

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

Keep in mind that in order to use this function the total number of elements in the array must remain the same.

Another way you do not need numpy:

>>> L=[1,2,3,4,5,6,7,8,9,10,11,12]
>>> fila = 4
>>> col = 3
>>> M = [L[col*i : col*(i+1)] for i in range(row)]

[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
    
answered by 22.04.2016 / 02:36
source
1

The following functional trick can be applied:

from itetools import zip_longest

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

args = [iter(L)]*ncols
M = list(zip_longest(*args))

Explanation :

  • an iterator is created from the list: iter(L)
  • the iterator is duplicated as many times as columns we want: [iter(L)]*ncols . All the items in this list are the same iterator, so if we now do a list([iter(L)]*ncols) we would get the first elements of the iterator, which are the first ncols items in the list L ( L[0:ncols] )
  • zip_longest combines lists as does the function zip , but filling the shortest lists until the longest list is reached (You could pass an argument to indicate with what value to fill the shortest lists).
  • the list of iterators is passed to the function zip_longest as a multiple argument. It is equivalent to doing zip_longest(it, it,...,it) as many times as the value of ncols . In this way, a value of each argument is taken in order to create the first row, the second row continues, and so on until there are no more left. Since all the arguments are the same iterator, values will be extracted from it until it is exhausted.
  • As I said, if the number of items were not enough to fill the last row, you could indicate zip_longest to do so with a default value:

    # para rellenar con ceros
    M = list(zip_longest(*args, fillvalue=0))
    
        
    answered by 22.04.2016 в 10:18