Python 如何从多维数组中返回最高值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15917076/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:22:00  来源:igfitidea点击:

How to return the highest value from a multi dimensional array?

pythonnumpy

提问by Abe Miessler

Say I have a multi dimensional array like the following:

假设我有一个多维数组,如下所示:

[
   [.1, .2, .9],
   [.3, .4, .5],
   [.2, .4, .8]
]

What would be the best* way to return a single dimension array that contains the highest value from each sub-array ([.9,.5,.8])? I assume I could do it manually doing something like below:

返回包含每个子数组 ( [.9,.5,.8]) 中最高值的一维数组的最佳方法是什么?我假设我可以手动执行以下操作:

newArray = []
for subarray in array:
   maxItem = 0
   for item in subarray:
       if item > maxItem:
           maxItem = item
   newArray.append(maxItem)

But I'm curious if there is a cleaner way to do this?

但我很好奇是否有更清洁的方法来做到这一点?

*In this case best = fewest lines of code

*在这种情况下最好=最少的代码行

采纳答案by wim

Since you mentioned in a comment that you are using numpy ...

由于您在评论中提到您正在使用 numpy ...

>>> import numpy as np
>>> a = np.random.rand(3,3)
>>> a
array([[ 0.43852835,  0.07928864,  0.33829191],
       [ 0.60776121,  0.02688291,  0.67274362],
       [ 0.2188034 ,  0.58202254,  0.44704166]])
>>> a.max(axis=1)
array([ 0.43852835,  0.67274362,  0.58202254])


edit:the documentation is here

编辑:文档在这里

回答by squiguy

Using a list comprehension:

使用列表理解:

maxed = [max(sub_array) for sub_array in array]

回答by Dogbert

mapwith maxis cleaner IMO.

mapmax更清洁的 IMO。

>>> arr = [
...    [.1, .2, .9],
...    [.3, .4, .5],
...    [.2, .4, .8]
... ]
>>> map(max, arr)
[0.9, 0.5, 0.8]

map documentation.

地图文档

回答by Joran Beasley

 map(max,my_array)

I think thats pretty short ...

我认为那很短...

回答by Ehsan

Maybe instead of the second for loop just use the maxfunction

也许而不是第二个 for 循环只使用max函数

回答by Evgenii

Try this:

尝试这个:

max(array.flatten())

回答by user3503711

You can use numpy

你可以使用 numpy

import numpy as np
w = [[2,3,4],[5,6,7],[1,2,11]]
h=[]
for i in w:
    h.append(np.amax(i))
print(h)