我需要检查gradscale中的数字是否以Numpy数组的形式存在于我的NxM矩阵中,如果数字8例如位于我的矩阵中,我想将该数字附加到一个空列表中,并将行号附加到另一个列表中 因此,我该如何检查矩阵中的数字是否不在Gradescale中,我尝试了不同类型的循环,但它们不起作用。
wrongNumber = []
Rows = []
gradeScale = np.array([-3,0,2,4,7,10,12])
if there is a number i matrix which is not i gradeScale
wrongNumber.append[number]
Rows.append[rownumber]
print("the grade {} in line {} is out of range",format(wrongNumber),
format(Rows))
答案 0 :(得分:1)
您可以使用numpy.ndarray.shape
浏览各行。
for row in range(matrix.shape[0]):
for x in matrix[row]:
if x not in gradeScale:
wrongNumber.append(x)
Rows.append(row)
此外,您没有正确使用format
。您的打印声明应为
print("The grade {} in line {} is out of range".format(wrongNumber, Rows))
以下帖子提供了有关格式化String formatting in Python的更多信息。
import numpy as np
wrongNumber = []
Rows = []
matrix = np.array([[1,2],[3,4],[5,6],[7,8]])
gradeScale = [1,3,4,5,8]
for row in range(matrix.shape[0]):
for x in matrix[row]:
if x not in gradeScale:
wrongNumber.append(x)
Rows.append(row)
print("The grades {} in lines {} (respectively) are out of range.".format(wrongNumber, Rows))
The grades [2, 6, 7] in lines [0, 2, 3] (respectively) are out of range
答案 1 :(得分:0)
您正在寻找带有enumerate()
的for循环。
示例:
for rowNumber, number in enumerate(matrix)
if number not in gradeScale:
wrongNumber.append[number]
Rows.append[rowNumber]