简体   繁体   中英

The 2D Array Index access, with step value

I have an array like:

a =np.array([[1,2,3,5,8,7,2,1,3,5,1,2,20,21],[3,8,3,9,8,7,10,1,3,5,1,2,20,21]])

requirement:

need to access index value with given step. For an example step value 3. Only index value not an elements value.

Required Output:

[[0,3,6,9,12],[0,3,6,9,12]]

Use a list comprehension to repeat the range for each row.

a =np.array([[1,2,3,5,8,7,2,1,3,5,1,2,20,21],[3,8,3,9,8,7,10,1,3,5,1,2,20,21]])
indexes = [list(range(0, a.shape[1], 3)) for _ in range(a.shape[0])]

You can do:

a = np.array([[1,2,3,5,8,7,2,1,3,5,1,2,20,21],[3,8,3,9,8,7,10,1,3,5,1,2,20,21]])
step = 3
indices = [np.arange(0, arr.size, step) for arr in a]

print(indices):

[array([ 0,  3,  6,  9, 12]), array([ 0,  3,  6,  9, 12])]

If you want lists instead of np arrays, just use .tolist() like:

[np.arange(0, arr.size, step).tolist() for arr in a]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM