Converting a flat list to a list of tuples

bonono at gmail.com bonono at gmail.com
Wed Nov 23 04:05:23 CET 2005


Bengt Richter wrote:
> On 22 Nov 2005 16:32:25 -0800, "bonono at gmail.com" <bonono at gmail.com> wrote:
>
> >
> >Bengt Richter wrote:
> >> On 22 Nov 2005 07:42:31 -0800, "George Sakkis" <gsakkis at rutgers.edu> wrote:
> >>
> >> >"Laurent Rahuel" wrote:
> >> >
> >> >> Hi,
> >> >>
> >> >> newList = zip(aList[::2], aList[1::2])
> >> >> newList
> >> >> [('a', 1), ('b', 2), ('c', 3)]
> >> >>
> >> >> Regards,
> >> >>
> >> >> Laurent
> >> >
> >> >Or if aList can get very large and/or the conversion has to be
> >> >performed many times:
> >> >
> >> >from itertools import islice
> >> >newList = zip(islice(aList,0,None,2), islice(aList,1,None,2))
> >> >
> >> Or, if you want to include fractional groups at the end
> >>
> >>  >>> aList = ['a', 1, 'b', 2, 'c', 3]
> >>  >>> from itertools import groupby
> >>  >>> def grouper(n):
> >>  ...     def git():
> >>  ...         while True:
> >>  ...             for _ in xrange(n): yield 0
> >>  ...             for _ in xrange(n): yield 1
> >>  ...     git = git()
> >>  ...     def grouper(_): return git.next()
> >>  ...     return grouper
> >>  ...
> >>  >>> [tuple(g) for _, g in groupby(aList, grouper(2))]
> >>  [('a', 1), ('b', 2), ('c', 3)]
> >>  >>> [tuple(g) for _, g in groupby(aList, grouper(3))]
> >>  [('a', 1, 'b'), (2, 'c', 3)]
> >>  >>> [tuple(g) for _, g in groupby(aList, grouper(4))]
> >>  [('a', 1, 'b', 2), ('c', 3)]
> >>
> >Personally, I would like to see it as [('a',1,'b',2), ('c',3,
> >None,None)],  as a list of tuple of equal length is easier to be dealt
> >with.
> >
> >i = iter(aList)
> >zip(i,chain(i,repeat(None)),
> >chain(i,repeat(None)),chain(i,repeat(None)))
> >
> Yes, but OTOH you might like to loop and catch ValueError when/if the last tuple
> doesn't unpack properly. Then you don't have to worry about None vs a sentinel :-)
>
That to me is a matter of style. I in general prefer the no
catch/except way of coding, the filter/map way(or the unix pipe way).
Not that one is better than another.

But I think your solution for this case is a bit hard to swallow. I
would rather do it the more imperative way of :

def split(s,n):
  a=[]
  c=0
  for x in s:
    a.append(x)
    c+=1
    if c%n == 0:
      yield a
      a=[]
  if a !=[]: yield a

list(split(aList,4))




More information about the Python-list mailing list