Python 我试图确定矩阵的最大元素,但不断得到错误(因为循环是必须的)
当我运行它时;它给出了此错误Python 我试图确定矩阵的最大元素,但不断得到错误(因为循环是必须的),python,valueerror,Python,Valueerror,当我运行它时;它给出了此错误 a = np.random.randint(1,100,(5,5)) max=a[0] for n in range(1,100): if(a[n] > max): max = a[n] print(max) if(a[n] > max): ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() o
a = np.random.randint(1,100,(5,5))
max=a[0]
for n in range(1,100):
if(a[n] > max):
max = a[n]
print(max)
if(a[n] > max):
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
我试图修复它,但又出现了另一个错误
a = np.random.randint(1,100,(5,5))
max=a[0]
for n in range(1,100):
if(a[n] > max):
max = a[n]
print(max)
if(a[n] > max):
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
再次运行时,会弹出此错误
a = np.random.randint(1,100,(5,5))
max=a[0]
for n in range(1,100):
if(a[n].all > max):
max = a[n]
print(max)
if(a[n].all>max):
TypeError:“您的第一个错误是因为a[n]
是一个列表(因为您的矩阵是二维的)
第二个错误是因为a[n]。all()
是一个函数,而不是一个属性-因此出现了()
。此外,如果n
第n行中的所有值都不是零(即truthy)而不是您想要的值,则返回True
要找到整个矩阵的最大值,您需要执行一些嵌套循环(或者将矩阵展平,然后按自己的方式执行单个循环)。尝试:
范围(5)内的i的:
对于范围(5)内的j:
如果[i][j]>最大值:
max_val=a[i][j]
您还需要将初始最大值更改为2D矩阵的第一个值,以便max_val=a[0][0]
但是,由于您使用的是numpy
,只需执行np.amax(a)
完整代码应为:
a=np.random.randint(1100,(5,5))
max_val=a[0][0]
对于范围(5)中的i:
对于范围(5)内的j:
如果[i][j]>最大值:
max_val=a[i][j]
打印(最大值)
您应该尽可能避免for循环,让我们试试numpy.ndarray.max()函数:
if(a[n].all > max):
TypeError: '<' not supported between instances of 'int' and 'builtin_function_or_method'
有什么原因不能使用numpy.max()
和numpy.min()
?您有一个二维数组,但只在其中一个上循环。你正在做的是max=a[0]
,但是a[0]
是你矩阵中的一整行……对于这个问题,循环是必须的:(我的错,不要调用你的变量max
,这是一个Python函数。每次运行a=np.random.randint时,都可以调用它,比如max\u val
,或者max\code>@SadStudent(5,5))
它重新随机化了a
,所以它当然是一个不同的值