Most efficient unzip - inverse of zip?

Tim Hochberg tim.hochberg at ieee.org
Tue Mar 26 23:09:11 EST 2002


In this same vein, I like this (assuming you're using a fairly recent
version of Python):

>>> a = (1,2,3)
>>> b = (4,5,6)
>>> ab = zip(a, b)
>>> a1, b1 = zip(*ab)
>>> a1
(1, 2, 3)
>>> b1
(4, 5, 6)

-tim



"Christophe Delord" <christophe.delord at free.fr> wrote in message
news:3CA0ECAB.2070900 at free.fr...
> Hi,
>
> apply zip again on the zipped list :
>
>
> def unzip(l):
> return tuple(apply(zip,l))
>
> a = (1,2,3)
> b = (4,5,6)
>
> ab = zip(a,b)
> print "zip(a,b) =", ab
> print "unzip(ab) =", unzip(ab)
>
>
>
> zip(a,b) = [(1, 4), (2, 5), (3, 6)]
> unzip(ab) = ((1, 2, 3), (4, 5, 6))
>
>
> unzip([(1,4),(2,5),(3,6)]) will compute zip((1,4),(2,5),(3,6))
> zip can zip more than two lists :-)
> and zip((1,4),(2,5),(3,6)) is (1,2,3),(4,5,6)
>
>
> You can also use zip to transpose matrix.
>
>
> Pearu Peterson wrote:
>
> > Hi,
> >
> > What would be the most efficient way to unzip zipped sequences
> > in Python 2.2?
> >
> > For example, consider
> >
> >  a_b = zip(a,b)  # where a and b are some sequences
> >  a_b.sort()
> >  a,b = unzip(a_b)
> >
> > For a start, I have
> >
> > def unzip(seq):
> >   ns = range(len(seq[0]))
> >   r = [[] for i in ns]
> >   [r[i].append(s[i]) for i in ns for s in seq]
> >   return tuple(r)
> >
> > Is there any better algorithm for unzip?
> >
> > Regards,
> > Pearu
> >
> >
>
>
> --
> Christophe Delord
> http://christophe.delord.free.fr/
>





More information about the Python-list mailing list