如何用两个不同长度的一维数组arr1[]、arr2[]创建二维数组arr[][]
Got it, let's break this down for you. You want to create a 2D array arr[][] that wraps the combined result of two 1D arrays (with different lengths) into a single inner array. Here's how you can do this in a few common programming languages:
Python Implementation
In Python, this is super straightforward—you can concatenate the two lists and wrap the result in another list to form a 2D array:
arr1 = [1, 2, 3] arr2 = [4, 5] arr = [arr1 + arr2] print(arr) # Output: [[1, 2, 3, 4, 5]]
- The
+operator mergesarr1andarr2into a single flat list[1,2,3,4,5] - Wrapping this combined list in square brackets
[]turns it into a 2D list (Python's equivalent of a 2D array)
Java Implementation
In Java, you'll need to first create a new array to hold the combined elements, then initialize the 2D array with this merged array:
public class CombineArrays { public static void main(String[] args) { int[] arr1 = {1, 2, 3}; int[] arr2 = {4, 5}; // Create an array to hold all elements from arr1 and arr2 int[] combined = new int[arr1.length + arr2.length]; // Copy elements from arr1 to combined System.arraycopy(arr1, 0, combined, 0, arr1.length); // Copy elements from arr2 to the end of combined System.arraycopy(arr2, 0, combined, arr1.length, arr2.length); // Create the 2D array with combined as its only inner array int[][] arr = {combined}; // Verify the result for (int[] innerArr : arr) { for (int num : innerArr) { System.out.print(num + " "); } } // Output: 1 2 3 4 5 } }
- We first calculate the total length needed for the combined array (
arr1.length + arr2.length) System.arraycopyis used to efficiently copy elements from both source arrays into the combined array- Finally, we initialize the 2D array
arrwith the combined array as its single element
JavaScript Implementation
JavaScript offers multiple simple ways to achieve this, either with the concat() method or the spread operator:
const arr1 = [1, 2, 3]; const arr2 = [4, 5]; // Using concat() const arr = [arr1.concat(arr2)]; // Or using spread operator (alternative approach) // const arr = [[...arr1, ...arr2]]; console.log(arr); // Output: [[1, 2, 3, 4, 5]]
arr1.concat(arr2)merges the two input arrays into one flat array- Wrapping the merged result in
[]creates a 2D array (an array containing one inner array)
内容的提问来源于stack exchange,提问作者imnain
相关产品推荐
相关产品推荐

