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

George Sakkis george.sakkis at gmail.com
Sat Apr 11 18:36:47 EDT 2009


On Apr 11, 6:05 pm, ergconce... at googlemail.com wrote:
> On Apr 11, 11:18 pm, George Sakkis <george.sak... at gmail.com> wrote:
>
>
>
> > 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
>
> > 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 ]])
>
> Thanks very much - works fine! Now for a follow-up question:)
>
> Actually my original list called "mylist" contains 81217 elements - I
> shape those into
>
>
>
> >>> len(mylist)
> 81217
> >>> s = N.array(mylist)
> >>> s.shape = (241,337)
>
> which works because the "total size of new array must be
> unchanged" (241x337=81217)
>
> Now this "matrix" actually is a 2D colorcoded map - I want to plot
> this using the imshow splot routine in mayavi2..
>
> However, there might be a problem: I believe that sometimes my
> original array will not exactly contain 81217 elements, but maybe only
> 81216 or so. Nevertheless, I know that time x times y - structure will
> always be the same (that is, 241 columns). What is of interest to me
> is the first 241 x 241 part of the matrix anyway. Is there an easy way
> to reshape my original array into a symmetric 241x241 matrix?

Yes, use numpy.resize:

>>> s = N.resize(my_list, (241,241))

You should probably be able to find the answer to most of your
upcoming numpy questions at http://numpy.scipy.org/numpydoc/numpy.html
(especially the array functions,
http://numpy.scipy.org/numpydoc/numpy-9.html)

George



More information about the Python-list mailing list