简体   繁体   中英

Python, getting max value of an array with a simple loop

I am writing a simple loop to get the max value inside an array.

I know there is the function arr.max() but I'm just curious why the following code does not work.

import numpy as np
arr1 = np.arange(0,9).reshape(3,3)

max_value = arr1[0]
for i in arr1:
    if max_value > i:
        max_value = i
print(max_value)

which gives me:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last) <ipython-input-80-9fb1fcfa0948> in <module>
       1 max_value = arr1[0]
       2 for i in arr1:
 ----> 3     if i > max_value:
       4         max_value = i

 ValueError: The truth value of an array with more than one element is
 ambiguous. Use a.any() or a.all()

.reshape(3,3) reshapes your array, so it ends up being a two-dimensional 3×3 array:

>>> print(arr1)
[[0 1 2]
 [3 4 5]
 [6 7 8]]

As a result, arr1[0] isn't a scalar, it's itself a three-element array. You'd have to iterate over that again to find the maximum value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM