You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

一维NumPy数组报IndexError: too many indices for array错误求助

Fixing "IndexError: too many indices for array" in Your Array Reversion Code

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:

  1. range(1, max_len) skips the 0th index of ret, leaving that position uninitialized.
  2. The index calculation array[max_len - i] will go out of bounds when i = max_len - 1 (since array indices start at 0 and go up to max_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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 15:12:58