reshape a list?

Robert Kern robert.kern at gmail.com
Mon Mar 6 21:50:37 CET 2006


KraftDiner wrote:
> I have a list that starts out as a two dimensional list
> I convert it to  a 1D list by:
> 
> b = sum(a, [])
> 
> any idea how I can take be and convert it back to a 2D list?

Alternatively, you could use real multidimensional arrays instead of faking it
with lists.

  http://numeric.scipy.org

In [15]: import numpy

In [16]: tmp = numpy.arange(256)**2

In [17]: a = numpy.column_stack((a,)*256)

In [18]: a[:10,:10]
Out[18]:
array([[ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0],
       [ 1,  1,  1,  1,  1,  1,  1,  1,  1,  1],
       [ 4,  4,  4,  4,  4,  4,  4,  4,  4,  4],
       [ 9,  9,  9,  9,  9,  9,  9,  9,  9,  9],
       [16, 16, 16, 16, 16, 16, 16, 16, 16, 16],
       [25, 25, 25, 25, 25, 25, 25, 25, 25, 25],
       [36, 36, 36, 36, 36, 36, 36, 36, 36, 36],
       [49, 49, 49, 49, 49, 49, 49, 49, 49, 49],
       [64, 64, 64, 64, 64, 64, 64, 64, 64, 64],
       [81, 81, 81, 81, 81, 81, 81, 81, 81, 81]])

In [19]: a.shape
Out[19]: (256, 256)

In [20]: a.ravel()[:100]
Out[20]:
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       0, 0, 0, 0, 0, 0, 0, 0])

In [21]: a.ravel().shape
Out[21]: (65536,)

In [22]: b = numpy.reshape(a.ravel(), (256,256))

In [23]: b.shape
Out[23]: (256, 256)

In [24]: (a == b).all()
Out[24]: True



-- 
Robert Kern
robert.kern at gmail.com

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco




More information about the Python-list mailing list