You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

PyCharm中NumPy ndarray元素访问报错:未定义__getitem__的技术咨询

解决PyCharm中Numpy矩阵元素访问/赋值的提示问题

Hey there! Let's break down why you're seeing that PyCharm warning and fix your matrix code right away.

问题根源

Your code has a small but critical issue with how you're initializing the Numpy array:

  • m = range(row*col) creates a Python built-in range object, not a proper Numpy ndarray.
  • Even though you use reshape(m, (row, col)), this doesn't convert the range object into a fully functional Numpy array. That's why PyCharm is throwing the warning about ndarray not defining __getitem__—it's confused about the type of m.

修正后的代码

Here's two clean ways to fix this, starting with the most straightforward approach:

方法1:直接创建空的Numpy数组

import numpy as np  # 推荐这种导入方式,避免命名冲突

row = int(input())
col = int(input())
# 初始化指定形状和整数类型的空数组
m = np.zeros((row, col), dtype=int)

for i in range(row):
    for j in range(col):
        el = int(input())
        m[i, j] = el  # Numpy数组推荐用逗号分隔的索引语法

方法2:转换range为Numpy数组后reshape

If you prefer to stick closer to your original logic:

import numpy as np

row = int(input())
col = int(input())
# 先把range转成Numpy数组,再调整形状
m = np.array(range(row*col)).reshape(row, col)

for i in range(row):
    for j in range(col):
        el = int(input())
        m[i, j] = el

额外说明

  • Numpy数组的索引优先用m[i,j] instead of m[i][j]—the latter works but is less efficient and not the idiomatic way to index multi-dimensional Numpy arrays.
  • Why didn't this issue pop up in IDLE? IDLE has looser static code checking than PyCharm. Python's dynamic typing might let the original code run, but PyCharm is helping you catch potential type-related bugs early, which is one of its big advantages!

内容的提问来源于stack exchange,提问作者randomuser

火山引擎 最新活动