Is there an easier way to express this list slicing?
John Henry
john106henry at hotmail.com
Thu Nov 30 18:20:24 EST 2006
Paul McGuire wrote:
> "John Henry" <john106henry at hotmail.com> wrote in message
> news:1164917296.255080.149660 at j72g2000cwa.googlegroups.com...
> >
> > John Henry wrote:
> >
> >>
> >> 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?
> >
> > Maybe like:
> >
> > alist, blist, clist, dlist = newStr("ABCDEFGHIJ")[1,1,3,None]
> >
>
> No need to contort string, just expand on your earlier idea. I changed your
> class name to SplitUp to more more conventional (class names are usually
> capitalized), and changed slice to __call__. Then I changed the lens arg to
> *lens - note the difference in the calling format. Pretty close to what you
> have above. Also, reconsider whether you want the __init__ function
> list-ifying the input src - let the caller decide what to send in.
>
In fact, should be possible to make that any object the caller want to
send in...
> -- Paul
>
> class SplitUp(object):
> def __init__(self,src):
> self._src=list(src)
> def __call__(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")(1,1,3,None)
> print alist, blist, clist, dlist
>
> Prints:
> ['A'] ['B'] ['C', 'D', 'E'] ['F', 'G', 'H', 'I', 'J']
Thanks for the help,
More information about the Python-list
mailing list