Create a 2D List from a 1D List

I'm a bit new to Python, and I want to convert 1D-2D-list list, taking into account widthand lengththis matrix.

Say I have one list=[0,1,2,3], and I want to create a matrix for 2 by 2this list.

How can I get matrix [[0,1],[2,3]] width= 2, length= 2 from list?

+12
source share
3 answers

Try something like this:

In [53]: l = [0,1,2,3]

In [54]: def to_matrix(l, n):
    ...:     return [l[i:i+n] for i in xrange(0, len(l), n)]

In [55]: to_matrix(l,2)
Out[55]: [[0, 1], [2, 3]]
+25
source

I think you should use numpy, which is designed to work with matrices / arrays, not a list of lists. It will look like this:

>>> import numpy as np
>>> list_ = [0,1,2,3]
>>> a = np.array(list_).reshape(2,2)
>>> a
array([[0, 1],
       [2, 3]])
>>> a.shape
(2, 2)

Avoid calling a variable listas it obscures the built-in name.

+7
source

NumPy.

import numpy

length = 2
width = 2
_list = [0,1,2,3]
a = numpy.reshape(a, (length, width))
numpy.shape(a)

As long as you change the values ​​in your list and update the values ​​of 'length' and 'width' accordingly, you should not get any errors.

0
source

All Articles