使用-1为未知行重塑python数组并用None填充剩余空格

我有一个长度未知的数组(例如让我们使用 11)。所以数组是


[1,2,3,4,5,6,7,8,9,10,11]

我想重塑该数组,以便他将拥有 5 列和尽可能多的行。我知道我可以使用reshape(-1,5) 这种方式根据数组长度创建行。


但它给了我这个错误:


ValueError: cannot reshape array of size 11 into shape (5)

知道我该怎么做吗?期望的结果是:


[[1,2,3,4,5],

[6,7,8,9,10],

[11,None,None,None,None]]

我运行并收到此错误的代码是:


import numpy as np

a = np.array([1,2,3,4,5,6,7,8,9,10,11])    

print(np.reshape(a, (-1,5)))


呼啦一阵风
浏览 314回答 2
2回答

幕布斯6054654

你可以在没有 numpy 的情况下做到这一点。ar = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]n = 5reshaped = [ar[i: i + n] + [None] * (i + n - len(ar)) for i in range(0, len(ar), n)]您还可以将技巧与迭代器一起使用(块将在元组中):reshaped = list(zip(*[iter(ar + [None] * (n - len(ar) % n))] * n))您可以zip_longest()从 itertools 申请不None自己添加值:from itertools import zip_longestreshaped = list(zip_longest(*[iter(ar)] * n))

杨__羊羊

In [135]: res = np.empty((3,5), object)                                                                      In [136]: res                                                                                                Out[136]: array([[None, None, None, None, None],       [None, None, None, None, None],       [None, None, None, None, None]], dtype=object)In [137]: res.flat[:11] = np.arange(1,12)                                                                    In [138]: res                                                                                                Out[138]: array([[1, 2, 3, 4, 5],       [6, 7, 8, 9, 10],       [11, None, None, None, None]], dtype=object)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python