无法在Python的同一程序中使用附加和整形函数

问题描述

我正在编写一个代码,它将接受用户的输入并将其转换为矩阵。我在代码中使用了append()reshape()函数,并且要使用它们,我正在导入numpyarray库,但是这样做时出现了以下错误

回溯(最近一次通话最后一次):文件“”,第1行,在 文件“ C:\ Program Files \ JetBrains \ PyCharm 2020.2 \ plugins \ python \ helpers \ pydev_pydev_bundle \ pydev_umd.py“,第197行,位于运行文件中 pydev_imports.execfile(filename,global_vars,local_vars)#执行脚本文件“ C:\ Program Files \ JetBrains \ PyCharm 2020.2 \ plugins \ python \ helpers \ pydev_pydev_imps_pydev_execfile.py“,第18行,在execfile中 exec(compile(contents +“ \ n”,file,'exec'),glob,loc)文件“ C:/ Users / pc / PycharmProjects / pythonProject / matrix multliplication”, 第30行,在 new_arr = arr.reshape(i,j)AttributeError:“ array.array”对象没有属性“ reshape”

我的代码

from numpy import *
from array import *
print("Enter the details of 1st Matrix")
i = int(input("Enter the number of Rows"))
j = int(input("Enter the number of Columns"))
print("NOTE:Number of columns of 1st matrix should be equal to Number  of rows of 2nd matrix")
print("Enter the details of 2st Matrix")
m = int(input("Enter the number of Rows"))
n = int(input("Enter the number of Columns"))

if j == m:
    arr = array('i',[])
    arr1 = array('i',[])

    p = i * j
    q = m * n

    print("Enter the values for 1st matrix")

    for d in range(p):
        x = int(input("Enter the value"))
        arr.append(x)

    print("Enter the values for 2st matrix")

    for e in range(q):
        y = int(input("Enter the value"))
        arr1.append(y)

    new_arr = arr.reshape(i,j)
    new_arr1 = arr1.reshape(m,n)

    print(arr)
    print(arr1)
else:
    print("Invalid Input")

我想念什么?

解决方法

reshape是numpy提供的函数,可以在numpy数组上使用。要使用reshape,您需要将arr变量转换为numpy数组。

,

您制作了一个array.array(也可能是一个列表,[]

arr = array('i',[])   
p = i * j
print("Enter the values for 1st matrix")
for d in range(p):
    x = int(input("Enter the value"))
    arr.append(x)

arr仍然是array.array。阅读array文档。您看到任何reshape方法了吗?如果没有,请不要执行以下操作:

new_arr = arr.reshape(i,j)

array.array不是多维的。它只是平面列表的内存高效版本。在这样的迭代会话中,与内置list类相比,它没有任何好处。

这是输入值的简单交互方式:

In [143]: alist = []
In [144]: for _ in range(4):
     ...:     alist.append(int(input()))     # list append
     ...: 
1
3
5
2
In [145]: alist
Out[145]: [1,3,5,2]
In [146]: arr = np.array(alist)       # make a numpy.ndarray
In [147]: arr
Out[147]: array([1,2])
In [148]: arr = arr.reshape(2,2)      # this has a reshape method
In [149]: arr
Out[149]: 
array([[1,3],[5,2]])

或将所有值放在一行中

In [150]: alist = input().split()
1 3 5 2
In [151]: alist
Out[151]: ['1','3','5','2']
In [152]: arr = np.array(alist,dtype=int).reshape(2,2)
In [153]: arr
Out[153]: 
array([[1,2]])

请注意我用过

import numpy as np

这是标准做法。它使我们可以清楚地识别numpy函数,例如使用np.array

您的使用

from numpy import *
from array import *

会造成混乱。 array()是对numpy函数的调用还是对array的调用?允许*进口,但通常不鼓励进口。