Idiom for Getting Slices of a List

Travis Oliphant olipt at mayo.edu
Sat Apr 10 11:47:43 EDT 1999


> 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






More information about the Python-list mailing list