iterator question

Travis Oliphant oliphant.travis at
Fri Sep 29 22:11:57 CEST 2006

Neal Becker wrote:
> Any suggestions for transforming the sequence:
> [1, 2, 3, 4...]
> Where 1,2,3.. are it the ith item in an arbitrary sequence
> into a succession of tuples:
> [(1, 2), (3, 4)...]
> In other words, given a seq and an integer that specifies the size of tuple
> to return, then for example:
> seq = [a,b,c,d,e,f]
> for e in transform (seq, 2):
>   print e
> would return
> (a,b)
> (c,d)
> (e,f)

Well, if you have NumPy installed, then this is pretty easy to do by 
reshaping the 1-d array into a 2-d array:

import numpy as N

def transform(seq, num):
     a = N.array(seq)
     a.shape = (-1, num)
     return a

This would return a sequence object that would print using lists

If you really insisted on tuples, then you could either convert the 
elements by replacing the last line with

return [tuple(x) for x in a]

or use a "record-array":

import numpy as N

def transform(seq, num):
     a = N.asarray(seq)
     dt = a.dtype
     newdt = [('',dt)]*num
     return a.view(newdt).tolist()

This would return a list of tuples as requested.


More information about the Python-list mailing list