我想在 python 中将一维列表转换为二维列表。我找到了一种用 NumPy 来做的方法,但是当列表的长度不能被列数整除时,它会给出以下错误:
<块引用>ValueError: 无法将大小为 9 的数组重塑为形状 (4)
在长度不可整除的情况下,我想添加 none 来填充空格。像这样:
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
b = some_func(a)
print(b)
并且输出应该是:
[[1, 2, 3, 4],
[5, 6, 7, 8],
[9, None, None, None]]
请帮帮我。我当前的代码是:
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
a = numpy.reshape(a, (-1, 4))
print(a)
答案 0 :(得分:1)
首先,您可以用 None
值填充列表,使其与大小匹配
reshape_size = 4
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
a += [None]*(reshape_size - len(a) % reshape_size) if len(a)%4 != 0 else []
a = numpy.reshape(a, (-1, reshape_size))
print(a)
答案 1 :(得分:0)
这应该有效。
from math import ceil
def my_reshape(arr, cols):
rows = ceil(len(arr) / cols)
res = []
for row in range(rows):
current_row = []
for col in range(cols):
arr_idx = row * cols + col
if arr_idx < len(arr):
current_row.append(arr[arr_idx])
else:
current_row.append(None)
res.append(current_row)
return res