I want to loop in sublists. I achieve it by doing the following code.
def batchGenerator(samples, subsetSize):
i=0
while (i < (len(samples) - subsetSize + 1)):
yield samples[i: i + subsetSize]
i = i + subsetSize
Is there a more standard library function to do the same thing?
I want to use it like:
for subl in batchGenerator(range(100), 10):
print (max(subl))
Output:
9
19
29
39
49
59
69
79
89
99
Edit:
I want the trailing elements that are fewer than subsetSize
to be truncated, and I find @s3cur3 solution the most elegant for this case (compared to the solutions in a similar thread: What is the most "pythonic" way to iterate over a list in chunks?)
I also prefer that the output stays the same type, list
, numpy.array
, torch.Tensor
, etc