简体   繁体   中英

How to reverse a numpy array using loops

Given this numpy array:

 Input:  nums = np.array([0] * SIZE, dtype=int)
 Output: [ 10  20  30  40  50  60  70  80  90 100]

I need to reverse the array elements using a loop (not using a numpy command directly). So the desired outcome would be: [100, 90 ,80,....10]
How can you reverse these using a for or while loop structure?

Here is what I've got so far.

for i in range(len(arr)-1, -1, -1):
        print(arr[i])

This will print the reverse order, but how can store these elements back into the array in this reverse order?

I am aware that numpy has built in functions to do this, however I want to understand this from a first principals approach.

import numpy as np

nums = np.array([10,20,30,40,50,60,70,80,90,100], dtype=int)
rev = np.zeros(nums.size, dtype=int)
for i in range(nums.size):
    rev[nums.size - (i + 1)] = nums[i]

np.zeros(s, dtype=d) creates an array of size s filled with zeros of type d .

In this case rev is the reversed array and nums.size is the same as len(nums)

import numpy as np

nums = np.array([10,20,30,40,50,60,70,80,90,100], dtype=int)
rev = np.zeros(nums.size, dtype=int)
for i in range(nums.size):
    rev[nums.size - (i + 1)] = nums[i]

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