[Tutor] Re: Bunch lists into sublists via alternation

kevin parks kp87@lycos.com
Wed, 18 Jul 2001 21:34:29 +0900


I am trying to figure out how to take a sequence and split it up into sub-lists
by alternation. For example if i had a sequence like:

x = [1,2,3,4,5,6,7,8,9]

and i called a function that was: seqSplit(seq, sub-lists)

seqSplit(x,2)

would yield: ([1,3,5,7,9], [2,4,6,8,None]) # None pads lists that are short elements

and seqSplit(x,3) --> ([1,4,7], [2,5,8], [3,6,9])
and seqSplit(x,4) --> ([1,6] [2,7], [3,8], [4,9], [5,None])


I've got something that bunches up consecutive elements into sub-lists:

def bunch(mylist, times):
	"""package up list elements in sub-lists n at a time.
	
	x=[1,2,3,4,5,6,7,8,9]
	bunch(x,1) --> [[1], [2], [3], [4], [5], [6], [7], [8], [9]]
	bunch(x, 2) --> [[1,2], [3,4], [5,6], [7,8], [9, None]
	bunch(x, 3) --> [[1,2,3], [4,5,6], [7,8,9]]
	bunch(x, 4) --> [1,2,3,4], [5,6,7,8] [9, None, None, None]]"""

	out = [mylist[i:i+times] for i in range(0, len(mylist), times)]
	if out:
		out[-1].extend([None] * (times - len(out[-1])))
	return out
 
# -- ---------------------------------------
 
But i can't figure out how to get the:

a = (1,9,1,9,1,9)
b = (1,9,7,1,9,7,1,9,7)
seqSplit(a,2) --> ([1, 1, 1], [9, 9, 9])"""
seqSplit(b,3) --> ([1, 1, 1], [9, 9, 9], [7, 7, 7])"""
	
	
type arrangement, particularly since i want it to work for any unpredetermined
number of sub-lists. I've got a kludge that works only for the case of seqSplit(x,2),
but i can't get anything to work for seqSplit(x,n) where n is anything else.

cheers,
kevin parks
seoul, korea




Get 250 color business cards for FREE!
http://businesscards.lycos.com/vp/fastpath/