为何init_all_x(5, 3.5).shape无法运行?求正确代码
问题分析与解决方案
报错原因
你的代码存在两个核心问题:
- 错误覆盖了numpy内置函数
np.all,将其赋值为普通Python列表[x]*n,而普通列表没有.shape属性,这是调用.shape时报错的直接原因。 - 返回的是普通列表,并非题目要求的numpy数组类型,自然无法使用numpy数组专属的
.shape属性。
正确代码
方法一:使用numpy内置full函数(推荐)
这是创建指定值填充数组最直接的方式:
import numpy as np def init_all_x(n, x): return np.full(n, x)
方法二:将列表转换为numpy数组
如果习惯用列表生成的方式,记得转成numpy数组:
import numpy as np def init_all_x(n, x): return np.array([x]*n)
验证
调用init_all_x(5, 3.5).shape会返回(5,),符合预期;调用init_all_x(5, 3.5)会输出array([3.5, 3.5, 3.5, 3.5, 3.5]),完全匹配题目要求。
内容的提问来源于stack exchange,提问作者Phung Doan
相关产品推荐
相关产品推荐

