如何将长度为n的列表转换为(n/2)×(n/2)的二维NumPy数组
Shortest way to chunk a flat array into fixed-size subarrays
If you're using Python, the shortest and cleanest way to get your desired 2D array (without creating intermediate lists first) is with a list comprehension that uses stepwise slicing:
original = [3, 1, 2, 4, 4, 2, 3, 1, 1, 3, 4, 2, 2, 4, 1, 3] chunked = [original[i:i+4] for i in range(0, len(original), 4)]
Running this code outputs exactly what you're looking for:
[[3, 1, 2, 4], [4, 2, 3, 1], [1, 3, 4, 2], [2, 4, 1, 3]]
Breakdown of the approach:
range(0, len(original), 4)generates the starting positions for each chunk: 0, 4, 8, 12 (since your array has 16 elements, which divides evenly by 4).- For each starting index
i, we slice the original array fromitoi+4—this creates each 4-element subarray directly. - The list comprehension wraps all these slices into the final 2D array in one go, no extra steps required.
This method is concise, efficient, and avoids any unnecessary intermediate steps like splitting into separate lists before combining them into the 2D structure.
内容的提问来源于stack exchange,提问作者Karthik Mohan
相关产品推荐
相关产品推荐

