Python错误集锦:创建numpy数组时TypeError: Tuple must have size 2, but has size 3

原文链接:http://www.juzicode.com/archives/2831

错误提示:

创建numpy数组时TypeError: Tuple must have size 2, but has size 3:

import numpy as np
a = np.array((1,2,3),(4,5,6))
print('a=\n',a)
 --------------------------------------------------------------------------- TypeError                                 Traceback (most recent call last) <ipython-input-5-ffd07b8e50c1> in <module>       1 import numpy as np ----> 2 a = np.array((1,2,3),(4,5,6))       3 print('a=\n',a) TypeError: Tuple must have size 2, but has size 3 

错误原因:

1、利用numpy.array()创建数组时,第2个位置参数不指明参数名称时默认应该是dtype,上面的例子中第二个位置参数是(4,5,6)的tuple类型,不符合dtype的类型要求。上面的例子中原意是要创建一个二维数组,应该在第一个位置参数上用嵌套的list或者tuple表示。

解决方法:

1、创建输入传入的数组第1个位置参数用一个tuple或者list表示,如果要创建二维或多维数组,要用嵌套的tuple或者list表示,第二个位置参数要么指明默认参数名称为dtype,如果不使用dtype指明,需要注意第二个位置参数的含义是dtype。

import numpy as np
a = np.array(((1,2,3),(4,5,6)))
print('a=\n',a)
import numpy as np
a = np.array([(1,2,3),(4,5,6)])
print('a=\n',a)
import numpy as np
a = np.array([(1,2,3)],dtype='int8')
print('a=\n',a)
print(a.shape)

关注微信公众号:“桔子code”,欢迎后台留言撩我,我会尽我所能为你解惑Python,C等编程知识

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注