【发布时间】:2015-07-21 22:01:54
【问题描述】:
我在 Windows 7 上使用 Python 2.7.5。由于某种原因,当我在 if 语句中使用我的 numpy 数组的维度之一和比较器时,python 不喜欢它:
a = np.array([1,2,3,4])
# reshapes so that array has two dimensions
if len(np.shape(a)) == 1:
a = np.reshape(a, (1, np.shape(a)))
b = np.shape(a)[0]
if b <= 3:
print 'ok'
我创建了一个 1D numpy 数组(实际上“a”是一个可能是 1D 或 2D 的输入)。然后我重塑它以形成一个 2D numpy 数组。我尝试将新创建的维度的大小用作比较器,但出现错误:“TypeError: an integer is required”
我还尝试了“int(b)”在 if 语句中将长整数转换为纯整数,它给出了相同的错误。如果我执行“type(b)”,它会给我“type 'long'”。我觉得好像我以前做过这个没有任何问题,但我找不到任何例子。我如何将一维数组更改为二维数组?任何帮助表示赞赏。
【问题讨论】:
-
哪一行报错?
-
np.shape(a)将是一个元组,因此当您执行(1, np.shape(a))时,您最终会在元组中得到一个元组 -
抱歉没有更具体。第二个 if 语句抛出错误“if b
标签: python numpy int long-integer shape