You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取给定3D numpy数组的行最大值并返回长度为3的列表

Solution to Extract Top 3 Row Max Values from 3D NumPy Array

Got it, let's work through this problem step by step. Your goal is to take a 3D NumPy array, calculate the maximum value for every individual row across the entire array, then return the top 3 largest of those max values sorted in descending order (matching your expected output [7,6,5]).

Step 1: Understand the Array Structure

First, let's confirm the shape of your input array:

import numpy as np

myArray = np.array([[[1,1,5], [1,1,1], [1,6,1]], [[2,2,2], [2,3,2], [2,2,2]], [[3,3,1], [7,1,1], [1,3,3]]])
print(myArray.shape)  # Output: (3, 3, 3)

This means we have 3 separate 3x3 2D arrays. Each "row" we care about is the innermost 1D array (e.g., [1,1,5], [7,1,1], etc.).

Step 2: Calculate Max for Each Row

To get the maximum value of every row, we use np.max() with axis=2—this targets the innermost dimension (the elements in each row) and computes the max for each row:

row_maxes = np.max(myArray, axis=2)
# row_maxes will look like this:
# array([[5, 1, 6],
#        [2, 3, 2],
#        [3, 7, 3]])

Now we have a 2D array where each element is the max of a single row from the original 3D array.

Step 3: Flatten and Get Top 3 Max Values

Next, we flatten this 2D array into a 1D list of all row maxes, then sort it in descending order and take the first 3 elements:

Option 1: Using Python's built-in sorted()

all_row_maxes = row_maxes.flatten()
top_three = sorted(all_row_maxes, reverse=True)[:3]
print(top_three)  # Output: [7, 6, 5]

Option 2: Using NumPy's sorting (more efficient for large arrays)

top_three = np.sort(row_maxes.flatten())[::-1][:3].tolist()
print(top_three)  # Output: [7, 6, 5]

One-Liner Version

If you prefer a concise solution, you can combine all steps into one line:

result = np.sort(np.max(myArray, axis=2).flatten())[::-1][:3].tolist()
print(result)  # Output: [7, 6, 5]

内容的提问来源于stack exchange,提问作者Elhanan Schwarts

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 21:18:11