Idiom for Getting Slices of a List

Joe Strout joe at strout.net
Sat Apr 10 13:59:09 EDT 1999


[[ This message was both posted and mailed: see
   the "To," "Cc," and "Newsgroups" headers for details. ]]

In article
<Pine.SUN.3.95-heb-2.07.990410102503.23259A-100000 at sunset.ma.huji.ac.il>,
 Moshe Zadka <moshez at math.huji.ac.il> wrote:

> I want a clean, and relatively efficient method to do the following:
> I have an array of length, n*m and I want to make it an array of 
> length m, where each member is an array of length n.
> 
> Example: n=2, m=3
> [0, 1, 2, 3, 4, 5] ==> [[0, 1], [2, 3], [4, 5]]

Well, if you want efficient and clean you should use Numeric...

>>> import Numeric
>>> a = Numeric.array( [0, 1, 2, 3, 4, 5] )
>>> a
array([0, 1, 2, 3, 4, 5])
>>> a.shape = (3,2)
>>> a
array([[0, 1],
       [2, 3],
       [4, 5]])

That last item is equivalent to the nested list-of-lists you asked for. 
(Note: to be picky, it's not an array unless you make it an array using
either the array module or the Numeric module.  What you illustrated
looked like a list of lists.)

Cheers,
-- Joe

-- 
,------------------------------------------------------------------.
|    Joseph J. Strout           Biocomputing -- The Salk Institute |
|    joe at strout.net             http://www.strout.net              |
`------------------------------------------------------------------'
Check out the Mac Web Directory!    http://www.strout.net/macweb.cgi




More information about the Python-list mailing list