Bunch lists into sublists via alternation

Tom Good Tom_Good1 at excite.com
Thu Jul 19 16:57:15 EDT 2001


kp87 at lycos.com (kevin parks) wrote in message news:<5e8bd451.0107190415.7cc17f93 at posting.google.com>...
> I've asked this on another list and never got a reply. Possibly
> because i have worn out my welcome with all my dumb questions, or
> because it is such a dumb question people hurt themselves laughing and
> are now all in the hospital.
> 
> 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

Or another way:

>>> def group(mylist, times, offset):
... 	return [mylist[i] for i in range(offset, len(mylist), times)]
... 
>>> def seqSplit(mylist, times):
... 	return [group(mylist, times, offset) for offset in range(times)]
... 
>>> seqSplit((1,9,1,9,1,9), 2)
[[1, 1, 1], [9, 9, 9]]
>>> seqSplit((1,9,7,1,9,7,1,9,7), 3)
[[1, 1, 1], [9, 9, 9], [7, 7, 7]]
>>>



More information about the Python-list mailing list