Python Forum
itertool islice why no negative values ?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
itertool islice why no negative values ?
#1
About itertool islice.

Why islice doesn't support negative values ?

( I realized than negative index need oftn the len() of something, it might need a complete generation of the list to get this, but for some generators and some different iterators might not ... )

Here my snippet, maybe someone can do better :)
(of course here im using a range, instead of some generators or iterators)


import itertools as it

def xislice(iterable, *args):
    #xislice(coll,stop)
    #xislice(coll,start,stop,[step])
    #handle negative args

    sz = len(args)
    if sz == 0:
        start = 0
        stop = len(iterable)
        step = 1
    elif sz == 1:
        start = 0
        stop = args[0] if args[0] != None else len(iterable)
        step = 1
    elif sz == 2:
        start = args[0] if args[0] != None else 0
        stop = args[1] if args[1] != None else len(iterable)
        step = 1
    else:
        start = args[0] if args[0] != None else 0
        stop = args[1] if args[1] != None else len(iterable)
        step = args[2] if args[2] != None else 1

    for x in range(start, stop, step):
        yield iterable[x]



xx = list(range(0,20))
yy = [x for x in it.islice(xx,1,None,2)]
print(yy)

yy = [x for x in xislice(xx,1,None,2)]
print(yy)

yy = [x for x in xislice(xx,15,-1,-2)]
print(yy)

#yy = [x for x in it.islice(xx,15,-1,-2)]
Reply
#2
You might want to compare this with more_itertools.islice_extended()
Reply
#3
Interesting, I didn't had the time to search for others implementations, but I will .
Thanks for the pointers :)
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020