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

如何在Julia中实现类似np.stack_column的数组列合并堆叠?

Interleaving Two 1D Arrays in Julia (Matching Your Desired Output)

Hey there! Let's break down how to get your desired array c = [1,4,2,5,3,6] from a = [1,2,3] and b = [4,5,6] in Julia—this is essentially interleaving the elements of the two arrays then flattening them, which aligns with the workflow you mentioned using np.column_stack in Python (followed by flattening).

Method 1: hcat + vec (Most Direct Python Equivalent)

This mirrors the Python approach: first stack the arrays column-wise into a 2D array, then flatten it column-first (which is Julia's default behavior):

a = [1, 2, 3]
b = [4, 5, 6]

# Stack columns first, then flatten column-wise
c = vec(hcat(a, b))
# Output: [1, 4, 2, 5, 3, 6]

hcat(a, b) creates the 2D array [1 4; 2 5; 3 6], and vec() converts it to a 1D array by reading elements column by column—perfect for your needs.

Method 2: Generator Expression (More Explicit Interleaving)

If you want to build the array directly by interleaving elements, a nested generator expression works great:

a = [1, 2, 3]
b = [4, 5, 6]

# Iterate over paired elements from a and b, then flatten each pair
c = [x for pair in zip(a, b) for x in pair]
# Output: [1, 4, 2, 5, 3, 6]

zip(a, b) creates tuples (1,4), (2,5), (3,6), and the inner loop unpacks each tuple to build the interleaved sequence.

Method 3: reshape + Transpose (Alternative Syntax)

You can also use reshape with a transpose to achieve the same result:

a = [1, 2, 3]
b = [4, 5, 6]

# Row-stack, transpose, then flatten
c = reshape([a b]', :)
# Output: [1, 4, 2, 5, 3, 6]

[a b] stacks the arrays into a row-wise 2D array, transposing it swaps rows and columns, and reshape(:,:) flattens it column-first.

All these methods will give you the exact output you're looking for—pick the one that fits your coding style best!

内容的提问来源于stack exchange,提问作者Mohammad Saad

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:30:44