absolute newbie: divide a list into sublists (nested lists?) of fixed length

Mensanator mensanator at aol.com
Sun Apr 12 00:01:13 CEST 2009


On Apr 11, 4:18�pm, George Sakkis <george.sak... at gmail.com> wrote:
> On Apr 11, 4:14�pm, ergconce... at googlemail.com wrote:
>
>
>
>
>
> > Hi,
> > I have a list looking like
>
> > [ 0.84971586, �0.05786009, �0.9645675, �0.84971586, �0.05786009,
> > 0.9645675, 0.84971586, �0.05786009, �0.9645675, �0.84971586,
> > 0.05786009, �0.9645675]
>
> > and I would like to break this list into subsets of fixed length (say,
> > three elements), i.e. to convert the list into a form such as the one
> > generated by the following example code which I have found:
>
> > >>>import numpy
> > >>>s = numpy.random.random((3,3))
> > >>>s
>
> > array([[ 0.11916176, �0.96409475, �0.72602155],
> > � � � �[ 0.84971586, �0.05786009, �0.96456754],
> > � � � �[ 0.81617437, �0.845342 �, �0.09109779]])
>
> > How can I create such a 2d array (i.e., something like a symmetric
> > matrix) from my data?
>
> > Thanks in advance,
>
> > Bernard
>
> > PS: Note that the numpy import is not important here, it is just the
> > structure of the data that matters..
>
> The numpy import *is* important if you want to use numpy-specific
> features; there are many "tricks" you can do easily with numpy arrays
> that you have to write manually for, say, regular python lists. For
> example what you want to do is trivial with numpy:
>
> >>>import numpy as N
> >>> s = N.array([ 0.84971586, �0.05786009, �0.9645675, �0.84971586, �0.05786009,
>
> 0.9645675, 0.84971586, �0.05786009, �0.9645675, �0.84971586,
> 0.05786009, �0.9645675])>>> # convert to a 4by3 array in place
> >>> s.shape = (4,3)
> >>> s

What does numpy do if the original list has 13 elements?

>
> array([[ 0.84971586, �0.05786009, �0.9645675 ],
> � � � �[ 0.84971586, �0.05786009, �0.9645675 ],
> � � � �[ 0.84971586, �0.05786009, �0.9645675 ],
> � � � �[ 0.84971586, �0.05786009, �0.9645675 ]])
>
> HTH,
> George




More information about the Python-list mailing list