Most efficient unzip - inverse of zip?

kevin parks kp87 at lycos.com
Wed Mar 27 05:31:38 EST 2002


# Two unzippers! slightly different. first is from the python cookbook
# (there are 2 there this one was much better than the other, which
was
# slow and not as flexible The second one is from the tutor list and
is
# fast, plus it allows you to grab only certain unzipped portions

# Title: A function to 'unzip' simple list-like objects 
# Submitter: gyro funch (other recipes) Last Updated: 2001/08/28 
# Version no: 1.0 
# 
# Description: This function takes a list and pulls it apart into a
# user-defined number of pieces. It acts like a sort of reverse zip
# function (although it deals with only the very simplest cases).
# 
# 	-- Renamed: unlace(), was def unzip(p, n):

def unlace(p, n):
    """Split a list-like object, 'p', into 'n' sub-lists by taking
    the next unused element of the main list and adding it to the
    next sub-list. A list of tuples (the sub-lists) is returned.
    Each of the sub-lists is of the same length; if p%n != 0, the
    shorter sub-lists are padded with 'None'.
        Example:
        >>> unlace(['a','b','c','d','e'], 3)
        [('a', 'd'), ('b', 'e'), ('c', None)]
    """
    (mlen, lft) = divmod(len(p),n)          # find length of longest
sub-list
    if lft != 0: mlen += 1

    lst = [[None]*mlen for i in range(n)]   # initialize list of lists
        
    for i in range(len(p)):
        (j, k) = divmod(i, n)
        lst[k][j] = p[i]

    return map(tuple, lst)


#  Date: Fri, 13 Jul 2001 23:01:36 -0500
#  To: tutor at python.org
#  Cc: rob at jam.rr.com
#  From: "Christopher Smith" <csmith at blakeschool.org>
#  Subject: [Tutor] Unzip
#
#  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)

def unzip(l,*jj):
	"""Returns one or more of the elements in the tuples of l that were
zipped together.
	
	This code will unzip lists which have been zipped together.
	If you created a zipped list, l=zip(a,b,c), you can use unzip
	to extract one or more of the lists:
	>>> 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
	"""
	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



More information about the Python-list mailing list