Cool Python Trick -- Access repeating numbers

If you want to access a list of repeating numbers and the peiod is different from the array size you can avoid having to calculate for the edge case by using itertools like so:

import numpy as np
import itertools
 
data = np.arange(10)
endless_data = itertools.cycle(data)
# grab 7 from the array repeatedly,
np.fromiter(islice(a, 7), np.int)
# >>> array([0, 1, 2, 3, 4, 5, 6])
 
np.fromiter(islice(a, 7), np.int)
# >>> array([7, 8, 9, 0, 1, 2, 3])

Python

comments powered by Disqus