一维NumPy数组报IndexError: too many indices for array错误求助
Let's break down what's going wrong here and fix it step by step.
The Root Cause of the Error
Your core mistake is in how you initialize the ret array:
ret = np.array(max_len)
When you pass a single integer to np.array(), it creates a 0-dimensional numpy array (just a single scalar value), not a 1-dimensional array with length max_len. So when you try to assign to ret[i] later, you're trying to use an index on an array that doesn't support indexing at all—hence the IndexError: too many indices for array.
Additional Logic Issues
On top of that, your loop has two small flaws:
range(1, max_len)skips the 0th index ofret, leaving that position uninitialized.- The index calculation
array[max_len - i]will go out of bounds wheni = max_len - 1(since array indices start at 0 and go up tomax_len - 1).
Fixed Code
Here's the corrected version of your function that addresses all these issues:
import numpy as np def revert_array(array): max_len = len(array) # Create a 1D array matching the input's data type, initialized to 0s ret = np.zeros(max_len, dtype=array.dtype) for i in range(max_len): # Map current index to the reversed position in the input array ret[i] = array[max_len - 1 - i] return ret a = np.array([1,2,3,4]) r = revert_array(a) print(r) # Output: [4 3 2 1]
A More Efficient Numpy-native Alternative
Since you're using numpy, you don't even need a loop to reverse the array—numpy has built-in slicing for this that's both cleaner and faster for large arrays:
a = np.array([1,2,3,4]) r = a[::-1] # Reverses the array in one line print(r) # Output: [4 3 2 1]
内容的提问来源于stack exchange,提问作者mrCarnivore

