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?
CodePudding user response:
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
CodePudding user response:
You can use % operator. n is your input
for i in range(len(a)):
a[(i n)%len(a)] ....
CodePudding user response:
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
CodePudding user response:
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