如何从多维数组返回最大值?

2024-04-23 10:11:34 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

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

但我很好奇是否有更干净的方法来做这个?

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


Tags: 方法代码inforif情况数组手动
3条回答

mapmax在IMO中更干净

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

map documentation

既然你在评论中提到你正在使用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])

编辑:文档是here

试试这个:

max(array.flatten())

相关问题 更多 >