Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/346.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 我试图确定矩阵的最大元素,但不断得到错误(因为循环是必须的)_Python_Valueerror - Fatal编程技术网

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
,所以它当然是一个不同的值