我试图确定矩阵的最大元素,但不断收到错误(For 循环是必须的)

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: '<' not supported between instances of 'int' and 'builtin_function_or_method'


汪汪一只猫
浏览 44回答 2
2回答

温温酱

您的第一个错误是因为它a[n]是一个列表(因为您的矩阵是二维的)。你的第二个错误是因为a[n].all()是一个函数,而不是一个属性 - 因此(). 另外,如果第 ' 行中的所有值n都非零(即 true),它只会返回 True - 这不是您想要的。要找到整个矩阵的最大值,您需要执行一些嵌套循环(或展平矩阵并按照您的方式执行单个循环)。尝试:for i in range(5):&nbsp; &nbsp; for j in range(5):&nbsp; &nbsp; &nbsp; &nbsp; if a[i][j] > max_val:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; max_val = a[i][j]您还需要将初始最大值更改为二维矩阵的第一个值,因此max_val = a[0][0]。但是,既然您正在使用numpy,那就这样做吧np.amax(a)。完整代码应该是:a = np.random.randint(1,100,(5,5))max_val = a[0][0]for i in range(5):&nbsp; &nbsp; for j in range(5):&nbsp; &nbsp; &nbsp; &nbsp; if a[i][j] > max_val:&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; max_val = a[i][j]print(max_val)

ibeautiful

您应该尽可能避免 for 循环,让我们尝试一下numpy.ndarray.max()函数:max = a.max()print(max)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python