首页 > 解决方案 > 如何在 python 中使用 np.zeros 作为迭代器?

问题描述

我正在尝试用 制作一个矩阵numpy,然后打印它(我这样做是因为稍后我想用更多矩阵进行数学运算),我得到的错误是:

"IndexError: arrays used as indices must be of integer (or boolean) type".

我尝试np.zeros在 for 循环中使用数组,但它不起作用(我遇到了类似的错误)。

注意:我尝试使用该np.matrix函数(将其分配给np.zeros列和行的数组,但它也不起作用,然后我尝试了一个变体(您可以看到已注释,该np.ndarray))。

代码:

import numpy

def matrixes():
    col= int(input("Enter the number of columns\n"))
    row= int(input("Enter the number of rows\n"))
    print(col,row)
    nCol=numpy.zeros(col)
    nRow=numpy.zeros(row)
    list_col=[nCol]
    list_Row=[nRow]
    print(nCol, nRow)
    #nArray=numpy.ndarray(nCol,nRow).reshape(2,2)
    for i in list_col:
        for j in list_Row:
            print("Enter value ",nCol,nRow)
            a=int(input())
            nCol[i]=a
            nRow[j]=a
    print("The matrix is: ",nCol, nRow)


#def __init__():
a = int(input("Enter an option\n"
    "1. Matrixes\n"))
if a==1:
    matrixes()

标签: pythonnumpy

解决方案


构造 Numpy 数组的最常见选项是(当然)np.array,描述如下

numpy.array(object, dtype=None, copy=True, order='K', subok=False, ndmin=0)
Create an array.

您可能想研究整个描述,但最相关的是object论点 - 再次来自参考描述

参数:对象:array_like

数组、任何公开数组接口的对象、其 __array__方法返回数组的对象或任何(嵌套)序列。

特别是“任何(嵌套)序列”,您知道,可以使用list comprehension构建,例如,您可以构建一个这样的列表列表

>>> [[input() for col in range(3)] for row in range(2)]
1
2
3
4
5
6
[['1', '2', '3'], ['4', '5', '6']]
>>>

并将所述列表传递给array构造函数(在注意到我们需要从字符串转换为浮点数之后,即......)

>>> np.array([[float(input()) for col in range(3)] for row in range(2)])
...
array([[1., 2., 3.],                                                                                                                                   
       [4., 5., 6.]])                                                                                                                                  
>>>

有了这些基础,我们就可以写出这段代码了

nrows = int(input('How many rows? '))
ncols = int(input('How many columns? '))
A = np.array([[float(input('Enter element for row %d and column %d: '%(row,col)))
                 for col in range(ncols)] for row in range(nrows)])

值得一提的是,这样做会产生一个可能(不,这不是你的情况......)将被垃圾收集的列表的大列表,因此,如果效率是主要问题,创建一个空矩阵使用np.empty((nrows, ncols))然后做一个循环来用你的值填充它可能是更可取的:

nr = int(input('How many rows? '))
nc = int(input('How many columns? '))
A = np.empty((nr, n)) # note that the argument is the tuple (nr, nc)
for r in nr:
    for c in nc:
        A(r, c) = float(input('A(%d, %d) = '%(r, c)))

作为旁注,最好将input两个内部循环中的调用包装到一个函数中,该函数反复询问您的输入,直到提供有效数字

def real_input(prompt)
    while 1:
        str_val = input(prompt)
        try:
            num_val = real(str_val)
       except ValueError:
            # optionally print error message
            continue
       return num_val

这样您就不必在输入错误时重新启动整个输入过程。


推荐阅读