Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class IndexGenerator:
- ''' A lightweight Index Generator that support multi-dimensional shapes.
- Indices are genrated on-the-fly!
- # Args:
- - shape : tuple or list.
- # Usage
- import numpy as np
- array = np.ones((32,35,3,10))
- for index IndexGenerator(array.shape):
- print(array[index])
- '''
- def __init__(self,shape):
- self.shape = shape
- self.ndim = len(shape)
- self.counters = [0] * self.ndim
- self.has_next = len(shape)>0 and not 0 in shape
- def __iter__(self):
- return self
- def __next__(self):
- if not self.has_next:
- raise StopIteration
- return self.get_next_index()
- def increment_single_index(self,index):
- if self.counters[index] < self.shape[index] - 1:
- self.counters[index] += 1
- return False
- else:
- self.counters[index] = 0
- return True
- def get_next_index(self):
- next_index = tuple(self.counters)
- dim = -1
- while dim >= -self.ndim and self.increment_single_index(dim):
- dim -= 1
- if dim < -self.ndim:
- self.has_next = False
- return next_index
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement