1

I had a problem, and I solved it by creating a class:

class ArrayIter:
    def __init__(self, array):
        self.array = array
        self.index = 0

    def __getitem__(self, n):
        res = self.array[self.index: self.index + n]
        self.index += n
        return res

it can be used like this:

>>> a = np.arange(20)
>>> iter = ArrayIter(a)
>>> iter[3]
array([0, 1, 2])
>>> iter[3]
array([3, 4, 5])
>>> iter[6]
array([ 6,  7,  8,  9, 10, 11])

Now something tells me I have reinvented a wheel. Is there something in python's standard library that can do the same? Keep in mind that I'm using numpy arrays and not lists.

acmpo6ou
  • 840
  • 1
  • 12
  • 21

1 Answers1

0

Try generators:

a = np.arange(20)
it = iter(a)

def get(n):
    for _ in range(n):
        yield next(it)

print(list(get(2)))
print(list(get(3)))
print(list(get(10)))
print(list(get(1)))

# [0, 1]
# [2, 3, 4]
# [5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
# [15]

Details: What does the "yield" keyword do?

zalevskiaa
  • 174
  • 5
  • 1
    Thank you for your help! There is a problem with this solution, though. The generator is creating a new list each time, while my solution only returns a view into numpy array. If I didn't miss anything. But your solution is still interesting. – acmpo6ou Sep 18 '22 at 08:59