如何从多维数组返回最大值? [英] How to return the highest value from a multi dimensional array?

查看:86
本文介绍了如何从多维数组返回最大值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Say I have a multi dimensional array like the following:

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

返回包含每个子数组([.9,.5,.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:

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

推荐答案

自从您在评论中提到您正在使用numpy ...

Since you mentioned in a comment that you are using 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

这篇关于如何从多维数组返回最大值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆