Is there an easier way to express this list slicing?
ptmcg at austin.rr._bogus_.com
Thu Nov 30 20:34:04 CET 2006
"John Henry" <john106henry at hotmail.com> wrote in message
news:1164913125.509492.54060 at 79g2000cws.googlegroups.com...
> If I have a list of say, 10 elements and I need to slice it into
> irregular size list, I would have to create a bunch of temporary
> variables and then regroup them afterwords, like:
> # Just for illustration. Alist can be any existing 10 element list
> That obviously work but do I *really* have to do that?
> BTW: I know you can do:
> but I don't see that it's any better.
The slicing notation is about the best general solution.
If you are doing this a lot, you should write some sort of "break up the
list function". Here's one that takes a list of list lengths to break the
ret = 
cur = 0
for var,length in varmap:
if length is not None:
ret.append( a_list[cur:cur+length] )
cur += length
ret.append( a_list[cur:] )
origlist = list("ABCDEFGHIJ")
alist, blist, clist, dlist = splitUp( origlist, (1,1,3,None) )
print alist, blist, clist, dlist
['A'] ['B'] ['C', 'D', 'E'] ['F', 'G', 'H', 'I', 'J']
More information about the Python-list