3

So, I have this array:

a = [[ 1,  -1 ]
 [ 0,   1 ]
 [-1.5, -1 ]]  

I want to start an iteration from the second row, and continue iteration until I have passed through all the array (thus, iterate in this index order: 1, 2, 0).

How do I do this in Python/numpy?

SuperStormer
  • 4,997
  • 5
  • 25
  • 35
  • What have you tried so far? – cards Jul 17 '22 at 19:19
  • Does this answer your question? [How to iterate through list infinitely with +1 offset each loop](https://stackoverflow.com/questions/72677648/how-to-iterate-through-list-infinitely-with-1-offset-each-loop) – ogdenkev Jul 17 '22 at 19:24

4 Answers4

0

With numpy you can use numpy.roll:

a = [[ 1, -1 ], [ 0, 1 ], [-1.5, -1 ]]

np.roll(a, -1, axis=0)

Output:

array([[ 0. ,  1. ],
       [-1.5, -1. ],
       [ 1. , -1. ]])

Or, rolling the indices:

for i in np.roll(range(len(a)), -1):
   # do something
mozway
  • 194,879
  • 13
  • 39
  • 75
0

Using a list or tuple is possible just by using slice indexing.

>>> a = [1,2,3]
>>> a[1:]+a[:1]
[2, 3, 1]
>>> [*a[1:],*a[:1]] #or if you prefer..
[2, 3, 1]

using the extend method would be something like this:

>>> a = [1,2,3]
>>> b = a[1:]
>>> b.extend(a[1:])
>>> b
[2,3,1]

as the other answer suggested you could use np.roll(x,-1,axis=0) with numpy

to iterate you simply do a for loop and it's done:

a = [1,2,3]
b = a[:1]
b.extend(a[1:])
for x in b:
   print(x,end=' ')
# 2 3 1

or you could use the modulo operator:

from functools import partial
mod = lambda x,y:x%y
a = [1,2,3]
l = len(a)
for x in map(partial(mod,y=l),range(l+1)):
    print(a[x],end=' ')
>>> 2 3 1
XxJames07-
  • 1,833
  • 1
  • 4
  • 17
0

You can use % operator. n is your input

for i in range(len(a)):
    a[(i+n)%len(a)] ....
Alireza75
  • 513
  • 1
  • 4
  • 19
0

Try this code

start_idx=1
for i in range(a.size):
    print(a[(i//a.shape[1] + start_idx)%a.shape[0], i%a.shape[1]])

0
1
-1.5
-1
1
-1
padu
  • 689
  • 4
  • 10