Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeating list of indices

Tags:

python

list

numpy

I'm trying to create a list of indices that cycles from 0 to m - 1 and is of length n. I've thus far achieved this as follows:

import numpy as np
m = 7
n = 12
indices = [np.mod(i, m) for i in np.arange(n)]

which results in the following:

[0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4]

Is there a faster way to achieve this?

Thanks for any suggestions.

like image 746
alexjrlewis Avatar asked Jan 27 '23 10:01

alexjrlewis


1 Answers

You can use islice + cycle from itertools:

from itertools import islice, cycle

print(list(islice(cycle(range(7)), 12)))
# [0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4]
like image 118
Austin Avatar answered Jan 28 '23 23:01

Austin