简体   繁体   中英

Why is it possible to use Python vanilla max() to numpy.ndarray

ndarray is a datatype defined specifically in numpy, so I wonder why I can use the following:

import numpy as np
a = np.array([1,2,3,4])
max(a) --> 4

I assume that python converts this back to a list, but I don't understand how this is done automatically and how python "knows" HOW to convert it to a list?

In addition, this one doesn't work:

b = np.array([[1,2,3],[4,5,6]])
max(b)

so in this case, python obviously doesn't know HOW to convert this to a list. Why does numpy not automatically flatten the multidimensional array to a vector like this:

max(b.flatten(1))

thanks a lot in advance.

The Python function max does not expect just lists as an argument but instead accepts an iterable object as shown in the docs here:

max(iterable[, key])

It is not converting the numpy arrays to lists at all but is instead using the fact that numpy arrays are iterable (as are tuples, strings, etc).

The max function has the following arguments:

max(iterable[, key=func]) -> value
max(a, b, c, ...[, key=func]) -> value

In the numpy array case the numpy array is treated as an iterable. In the case of your b what will happen is that b gets iterated over. This results in:

>>> list(iter(b))
[array([1, 2, 3]), array([4, 5, 6])]

Now if you compare the two items with the default comparison function you'll get the same error:

>>> c = list(iter(b))
>>> cmp(c[0], c[1])

Numpy does not flatten the array as the iterator will loop, by default , over rows and not over elements. If you want more control over the iteration, you can use on of the array iterators such as:

the numpy.nditer function.

>>> max(np.nditer(b))
array(6)

or the .flat attribute:

>>> max(b.flat)
6

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