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

如何动态打印行长度不一致的二维数组的各列元素

Solution for Printing Jagged 2D Array Column-Wise

Got it, let's break down how to solve this problem—printing elements of a jagged (row-length inconsistent) 2D array in column order, dynamically adapting to any array structure.

Core Approach

The key here is to:

  1. First figure out the maximum number of columns present in any row of the array. This tells us how many columns we need to iterate through.
  2. For each column index, loop through every row and check if the row has an element at that column. If it does, print the element.
  3. Move to the next column once all rows are checked for the current column.

Python Implementation

Here's a clean, dynamic solution in Python:

def print_column_wise(jagged_arr):
    # Handle empty array case
    if not jagged_arr:
        return
    
    # Dynamically get the maximum number of columns across all rows
    max_columns = max(len(row) for row in jagged_arr)
    
    # Iterate over each column index
    for col_idx in range(max_columns):
        # Collect elements for the current column (or print directly)
        column_elements = []
        for row in jagged_arr:
            # Check if the row has this column to avoid index errors
            if col_idx < len(row):
                column_elements.append(str(row[col_idx]))
        # Print the column elements separated by space
        print(' '.join(column_elements))

# Test with your sample array
sample_array = [
    [1, 2],          # Row 0: 2 columns
    [3],             # Row 1: 1 column
    [4, 5, 6, 7],    # Row 2: 4 columns
    [8, 9],          # Row 3: 2 columns
    [10],            # Row 4: 1 column
    [11, 12, 13],    # Row 5: 3 columns
    [14],            # Row 6: 1 column
    [15]             # Row 7: 1 column
]

print_column_wise(sample_array)

Output for the Sample Array:

1 3 4 8 10 11 14 15
2 5 9 12
6 13
7

JavaScript Implementation

If you're working with JavaScript, here's an equivalent solution:

function printColumnWise(jaggedArr) {
    if (jaggedArr.length === 0) return;
    
    // Get maximum column count using spread operator and map
    const maxColumns = Math.max(...jaggedArr.map(row => row.length));
    
    for (let colIdx = 0; colIdx < maxColumns; colIdx++) {
        const columnElements = [];
        for (const row of jaggedArr) {
            if (colIdx < row.length) {
                columnElements.push(row[colIdx]);
            }
        }
        console.log(columnElements.join(' '));
    }
}

// Test with sample array
const sampleArray = [
    [1, 2],
    [3],
    [4, 5, 6, 7],
    [8, 9],
    [10],
    [11, 12, 13],
    [14],
    [15]
];

printColumnWise(sampleArray);

Why This Works

  • Dynamic Adaptability: By calculating max_columns on the fly, the code works for any jagged array—no hardcoded column counts needed.
  • Index Safety: The check col_idx < len(row) (or colIdx < row.length in JS) prevents index out-of-bounds errors, which is crucial when dealing with rows of varying lengths.
  • Clean Output: Collecting elements per column and then printing them ensures the output is grouped by column, matching your requirement.

内容的提问来源于stack exchange,提问作者Momo Shaheen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:53:23