[Tutor] Unzip

Christopher Smith csmith@blakeschool.org
Fri, 13 Jul 2001 23:01:36 -0500


Here's a piece of useless code which extracts lists that have been zipped 
together (or mapped together with None: 
	map(Nane,l1,l2) is the same as zip(l1,l2)

Does anyone use something else to do this?

---code start---
def unzip(l,*jj):
	'''Return all (if none are specified) or some 
	   elements in the tuples of l that were zipped together.
	'''
	#
	# Christopher P. Smith 7/13/2001
	#
	if jj==():
		jj=range(len(l[0]))
	rl = [[li[j] for li in l] for j in jj] # a list of lists
	if len(rl)==1:
		rl=rl[0] #convert list of 1 list to a list
	return rl

a=[1,2,3]
b=[4,5,6]
c=[7,8,9]
l=zip(a,b,c)

x,y,z= unzip(l) # get them all: x=[1,2,3], y=[4,5,6], z=[7,8,9]
y=unzip(l,1)    # get the 1th one: y as above
x,z=unzip(l,0,2)# get the 0th and 2th ones: x and z as above

---code end---

/c