xslice idea | a generator slice

Oscar Benjamin oscar.j.benjamin at gmail.com
Thu Jul 11 11:14:46 EDT 2013


On 11 July 2013 15:54, Russel Walker <russ.pobox at gmail.com> wrote:
> ...oh and here is the class I made for it.
>
> class xslice(object):
>     '''
>     xslice(seq, start, stop, step) -> generator slice
>     '''
>
>     def __init__(self, seq, *stop):

Wouldn't it be better if it has the same signature(s) as itertools.islice?

>         if len(stop) > 3:
>             raise TypeError("xslice takes at most 4 arguments")
>         elif len(stop) < 0:

How would len(stop) be negative?

>             raise TypeError("xslice requires atleast 2 arguments")
>         else:
>             start, stop, step = (((0,) + stop[:2])[-2:] +  # start, stop
>                                  (stop[2:] + (1,))[:1])    # step
>             stop = min(stop, len(seq))
>             self._ind = iter(xrange(start, stop, step))
>             self._seq = seq
>
>     def __iter__(self):
>         return self
>
>     def next(self):
>         return self._seq[self._ind.next()]
>
>
>
> Although now that I think about it, it probably should've just been a simple generator function.

Or you can use itertools.imap:

def xslice(sequence, start_or_stop, *args):
    indices = xrange(*slice(start_or_stop, *args).indices(len(sequence)))
    return imap(sequence.__getitem__, indices)


Oscar



More information about the Python-list mailing list