python - Return mini batch of items from generator -
i'm trying create class wraps generator function, can obtain items generator in batches of predefined size.
i.e. if had list of 10 random numbers , specified mini batch size of 2 i'd 5 tuples of 2 numbers.
i wrote following wrapper class generator function hoping job:
import random class multiple_lottery_draws(object): def __init__(self, num_draws): self.num_draws = num_draws print("initialized % draws"%self.num_draws) def my_lottery(self): # returns 9 numbers between 1 , 100 in range(10): yield random.randint(1, 100) # returns 10th number between 1000 , 2000 yield random.randint(1000,2000) def __iter__(self): data = [] in range(self.num_draws): data.append(next(iter(self.my_lottery()))) yield data two_draws = multiple_lottery_draws(2)
however, although generator works fine,
for in two_draws.my_lottery(): print # prints: 52,12,61,67,30,78,84,90,69,31,1069
if try obtain mini-batches wrapper class 1 item
for in two_draws: print # prints: [74, 95]
what doing wrong?
you call yield
once. try this:
def __iter__(self): data = [] in self.my_lottery(): data.append(i) if len(data) == self.num_draws: yield data data = [] if data: yield data
Comments
Post a Comment