Is there an easier way to express this list slicing?

Paul McGuire ptmcg at austin.rr._bogus_.com
Thu Nov 30 14:34:04 EST 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
> a_list=("",)*10
> (a,b,c1,c2,c3,d1,d2,d3,d4,d5)=a_list
> alist=(a,)
> blist=(b,)
> clist=(c1,c2,c3)
> dlist=(d2,d3,d4,d5)
>
> That obviously work but do I *really* have to do that?
>
> BTW: I know you can do:
> alist=a_list[0]
> blist=a_list[1]
> clist=a_list[2:5]
> dlist=a_list[5:]
>
> 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 
list into.

-- Paul


def splitUp(src,lens):
    ret = []
    cur = 0
    for var,length in varmap:
        if length is not None:
            ret.append( a_list[cur:cur+length] )
            cur += length
        else:
            ret.append( a_list[cur:] )
    return ret


origlist = list("ABCDEFGHIJ")
alist, blist, clist, dlist = splitUp( origlist, (1,1,3,None) )
print alist, blist, clist, dlist

Prints
['A'] ['B'] ['C', 'D', 'E'] ['F', 'G', 'H', 'I', 'J']





More information about the Python-list mailing list