假设我有一个多维数组,如下所示:
[
[.1, .2, .9],
[.3, .4, .5],
[.2, .4, .8]
]
Run Code Online (Sandbox Code Playgroud)
返回包含每个子数组([.9,.5,.8])中最高值的单维数组的最佳方法是什么?我假设我可以手动执行以下操作:
newArray = []
for subarray in array:
maxItem = 0
for item in subarray:
if item > maxItem:
maxItem = item
newArray.append(maxItem)
Run Code Online (Sandbox Code Playgroud)
但我很好奇是否有更清洁的方法来做到这一点?
*在这种情况下,最好=最少的代码行
Dog*_*ert 11
map与max更清洁的IMO.
>>> arr = [
... [.1, .2, .9],
... [.3, .4, .5],
... [.2, .4, .8]
... ]
>>> map(max, arr)
[0.9, 0.5, 0.8]
Run Code Online (Sandbox Code Playgroud)
地图文档.
wim*_*wim 11
既然你在评论中提到你正在使用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])
Run Code Online (Sandbox Code Playgroud)
编辑: 文档在这里