无法在 Python 中的同一程序中使用追加和重塑函数

Unable to use append and reshape functions in the same program in Python

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

Traceback (most recent call last): File "", line 1, in File "C:\Program Files\JetBrains\PyCharm 2020.2\plugins\python\helpers\pydev_pydev_bundle\pydev_umd.py", line 197, in runfile pydev_imports.execfile(filename, global_vars, local_vars) # execute the script File "C:\Program Files\JetBrains\PyCharm 2020.2\plugins\python\helpers\pydev_pydev_imps_pydev_execfile.py", line 18, in execfile exec(compile(contents+"\n", file, 'exec'), glob, loc) File "C:/Users/pc/PycharmProjects/pythonProject/matrix multliplication", line 30, in new_arr = arr.reshape(i,j) AttributeError: 'array.array' object has no attribute '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 class.

相比,它没有提供任何好处

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

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, 3, 5, 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, 3],
       [5, 2]])

注意我用了

import numpy as np

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

您对

的使用
from numpy import *
from array import *

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