Mailing List Archive

Idiom for Getting Slices of a List
Hi.

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]]

Anyone?

--
Moshe Zadka <mzadka@geocities.com>.
QOTD: What fun to me! I'm not signing permanent.
Idiom for Getting Slices of a List [ In reply to ]
> 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]]

If you have the Numeric extension:

from Numeric import reshape

>>> d = [0,1,2,3,4,5]
>>> n,m = 2,3
>>> f = reshape(d,(m,n)).tolist()
>>> print f
[[0, 1], [2, 3], [4, 5]]

Best,

Travis Oliphant
Idiom for Getting Slices of a List [ In reply to ]
[.[. 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@sunset.ma.huji.ac.il>,
Moshe Zadka <moshez@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@strout.net http://www.strout.net |
`------------------------------------------------------------------'
Check out the Mac Web Directory! http://www.strout.net/macweb.cgi