Python how to cycle through a predefined number of elements in an array

I am trying to create a function that always returns me a pre-fixed number of elements from an array that will be larger than the prefix number:

def getElements(i,arr,size=10): return cyclic array return 

where i denotes the index of the array to extract and arr represents the array of all elements:

Example:

 a = [0,1,2,3,4,5,6,7,8,9,10,11] b = getElements(9,a) >> b >> [9,10,11,0,1,2,3,4,5,6] b = getElements(1,a) >> b >> [1,2,3,4,5,6,7,8,9,10] 

where i = 9 and the array returns [9:11]+[0:7] to complete 10 elements with i = 1 do not need to loop the array, just get [1:11]

thanks for the help

Source code (doesn't work):

 def getElements(i,arr,size=10): total = len(arr) start = i%total end = start+size return arr[start:end] #not working cos not being cyclic 

EDIT:

I can not do import for this script

+5
source share
4 answers

You can come back

 array[i: i + size] + array[: max(0, i + size - len(array))] 

for instance

 In [144]: array = list(range(10)) In [145]: array Out[145]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] In [146]: i, size = 1, 10 In [147]: array[i: i + size] + array[: max(0, i + size - len(array))] Out[147]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] In [148]: i, size = 2, 3 In [149]: array[i: i + size] + array[: max(0, i + size - len(array))] Out[149]: [2, 3, 4] In [150]: i, size = 5, 9 In [151]: array[i: i + size] + array[: max(0, i + size - len(array))] Out[151]: [5, 6, 7, 8, 9, 0, 1, 2, 3] 
+3
source

itertools is a fantastic library with many interesting things. For this case we can use cycle and islice .

 from itertools import cycle, islice def getElements(i, a, size=10): c = cycle(a) # make a cycle out of the array list(islice(c,i)) # skip the first `i` elements return list(islice(c, size)) # get `size` elements from the cycle 

It works the way you like.

 >>> getElements(9, [0,1,2,3,4,5,6,7,8,9,10,11]) [9, 10, 11, 0, 1, 2, 3, 4, 5, 6] 
+3
source
 def get_elements(i, arr, size=10): if size - (len(arr) - i) < 0: return arr[i:size+i] return arr[i:] + arr[:size - (len(arr) - i)] 

Is this what you want? Updated to work with lower numbers.

+2
source
 a=[1, 2, 3] def cyclic(a, i): b=a*2 return b[i:i+len(a)] print(cyclic(a, 2)) 
+2
source

All Articles