Is there an easier way to express this list slicing?

John Henry john106henry at hotmail.com
Thu Nov 30 14:53:57 EST 2006


John Henry wrote:
> Paul McGuire wrote:
> > "Paul McGuire" <ptmcg at austin.rr._bogus_.com> wrote in message
> > news:MmGbh.10434$Gk5.6762 at tornado.texas.rr.com...
> > > "John Henry" <john106henry at hotmail.com> wrote in message
> > > news:1164913125.509492.54060 at 79g2000cws.googlegroups.com...
> > snip
> >
> > Grrrr... that's what I get for not keeping editor and interpreter windows in
> > sync.  My post was referencing vars I had defined in the interpreter, but
> > which the function had no clue of. !!!  Here's a working version.
> >
> > -- Paul
> >
> >
> > def splitUp(src,lens):
> >     ret = []
> >     cur = 0
> >     for length in lens:
> >         if length is not None:
> >             ret.append( src[cur:cur+length] )
> >             cur += length
> >         else:
> >             ret.append( src[cur:] )
> >     return ret
> >
> > origlist = list("ABCDEFGHIJ")
> > alist, blist, clist, dlist = splitUp( origlist, (1,1,3,None) )
> > print alist, blist, clist, dlist
>
>
> Nice.
>
> While we are at it, why not:
>
> class splitUp(object):
>    def __init__(self,src):
>        self._src=list(src)
>    def slice(self, lens):
>      ret = []
>      cur = 0
>      for length in lens:
>          if length is not None:
>              ret.append( self._src[cur:cur+length] )
>              cur += length
>          else:
>              ret.append( self._src[cur:] )
>      return ret
>
> alist, blist, clist, dlist = splitUp("ABCDEFGHIJ").slice((1,1,3,None))
> print alist, blist, clist, dlist
>
> Now, that's readable!

Further, if splitUp is a sub-class of string, then I can do:

alist, blist, clist, dlist = "ABCDEFGHIJ".slice((1,1,3,None))

Now, can I override the slice operator?




More information about the Python-list mailing list