在Python中合并数组为单个数组及将多维numpy数组转为一维数组
Hey there! Let's break down your two Python array questions step by step, with practical examples for each scenario.
1. Merging Multiple Arrays/Lists into One in Python
For Regular Python Lists
- Using the
+operator: This is the most straightforward method for standard lists—just add them directly:list_a = [1, 2, 3] list_b = [4, 5] list_c = [6] merged_list = list_a + list_b + list_c # Result: [1, 2, 3, 4, 5, 6] - Using
extend(): Ideal if you want to build the merged list incrementally. Start with an empty list and add each array's elements one by one:merged_list = [] merged_list.extend(list_a) merged_list.extend(list_b) merged_list.extend(list_c) - Using
itertools.chain: Perfect for large numbers of lists or when you want to avoid creating intermediate copies (more memory-efficient):from itertools import chain merged_list = list(chain(list_a, list_b, list_c))
For NumPy Arrays
If you're working with NumPy arrays, use np.concatenate() to combine them:
import numpy as np arr_a = np.array([1, 2]) arr_b = np.array([3, 4, 5]) merged_arr = np.concatenate([arr_a, arr_b]) # Result: array([1, 2, 3, 4, 5])
2. Converting Mixed-Dimension NumPy Arrays to a 1D Array
For your specific case where you have a tuple of NumPy arrays with varying dimensions, we first flatten each array to 1D, then concatenate them all together. Here's the exact solution:
Step-by-Step Code
import numpy as np # Your input tuple of mixed-dimension arrays l = (np.array([0.08]), np.array([[ 0.56, -0.01, 0.46]]), np.array([[ 0.60], [0.07], [0.03]]), np.array([[0., 0., 0., 0.]]), np.array([[0.]])) # Flatten each array in the tuple, then concatenate into one 1D array flattened_components = [arr.flatten() for arr in l] final_1d_array = np.concatenate(flattened_components) print(final_1d_array) # Output: array([0.08, 0.56, -0.01, 0.46, 0.6 , 0.07, 0.03, 0. , 0. , 0. , 0. , 0. ])
Quick Notes:
flatten()vsravel(): Both convert multi-dimensional arrays to 1D.flatten()returns a copy (safe if you don't want to modify the original array), whileravel()returns a view (more memory-efficient if you don't need to alter the flattened version). Either works for this task.- Typo Check: Your target result mentions missing
0.46from the second array inl—that's likely a mistake! The code above includes all elements as expected from your input.
内容的提问来源于stack exchange,提问作者Hana
相关产品推荐
相关产品推荐

