简体   繁体   English

为什么可以将Python vanilla max()用于numpy.ndarray

[英]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: ndarray是numpy中专门定义的数据类型,所以我想知道为什么我可以使用以下内容:

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? 我假设python将其转换回列表,但我不明白这是如何自动完成的以及python如何“知道”如何将其转换为列表?

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. 所以在这种情况下,python显然不知道如何将其转换为列表。 Why does numpy not automatically flatten the multidimensional array to a vector like this: 为什么numpy不会自动将多维数组展平为这样的向量:

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: Python函数max不希望仅将列表作为参数,而是接受一个iterable对象,如下文档中所示:

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). 它根本没有将numpy数组转换为列表,而是使用numpy数组可迭代的事实(如元组,字符串等)。

The max function has the following arguments: max函数具有以下参数:

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. 在numpy数组的情况下,numpy数组被视为可迭代的。 In the case of your b what will happen is that b gets iterated over. 对于你的b,将会发生的事情是b被迭代。 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. Numpy不会展平数组,因为迭代器默认会循环遍历行而不是元素。 If you want more control over the iteration, you can use on of the array iterators such as: 如果想要更多地控制迭代,可以使用数组迭代器,例如:

the numpy.nditer function. numpy.nditer函数。

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

or the .flat attribute: .flat属性:

>>> max(b.flat)
6

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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