Most efficient unzip - inverse of zip?

Christophe Delord christophe.delord at free.fr
Tue Mar 26 16:48:27 EST 2002


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