List
Mike C. Fletcher
mcfletch at rogers.com
Sun Jun 2 19:58:10 EDT 2002
I don't know if you'll consider this a more elegant way to divide up the
lists, but I think it's a little more beautiful than the index-mucking
approaches IMO:
def into( source, count=3 ):
source = source[:]
return intoDestructive( source, count )
def intoDestructive( source, count=3 ):
if source and not count:
raise ValueError( """Cannot divide into 0-length sub-elements""" )
elif not source:
return []
results = []
if count > 0:
while source:
results.append( source[:count])
del source[:count]
else:
while source:
results.append( source[count:])
del source[count:]
return results
It will be very slow for very large lists with positive slice values
(something the index-mucking approach doesn't suffer from), but for most
reasonably sized lists, should be fairly good. It handles negative
steps as well, so you can slice up the list from the right _or_ the left
side :) .
Enjoy all,
Mike
Chris Gonnerman wrote:
...
>
> Lists = []
> N = 2
>
> adj = 0
>
> if len(BigList)%N:
> adj = 1
>
> for i in range(len(BigList)/N+adj):
> Lists.append(BigList[i*N:(i+1)*N])
>
> (If anyone knows a more elegant solution please post it,
> as I am getting headaches trying to think of one.)
...
_______________________________________
Mike C. Fletcher
http://members.rogers.com/mcfletch/
More information about the Python-list
mailing list