我有一個包含奇數個元素的列表。我想把它轉換成特定的尺寸。我的代碼:alist = ['a','b','c']cols= 2rows = int(len(alist)/cols)+1 # 2anarray = np.array(alist.extend([np.nan]*((rows*cols)-len(months_list)))).reshape(rows,cols)當前輸出:ValueError: cannot reshape array of size 1 into shape (2,2)預期輸出:anarray = [['a','b'],['c',nan]]
3 回答

翻翻過去那場雪
TA貢獻2065條經驗 獲得超14個贊
你可以試試:
out = np.full((rows,cols), np.nan, dtype='object') out.ravel()[:len(alist)] = alist
輸出:
array([['a', 'b'], ['c', nan]], dtype=object)
作為旁注,這可能對您更好:
rows = int(np.ceil(len(alist)/cols))

Qyouu
TA貢獻1786條經驗 獲得超11個贊
嘗試(沒有任何外部庫)
import math
alist = ['a', 'b', 'c']
cols = 2
new_list = []
steps = math.ceil(len(alist) / cols)
start = 0
for x in range(0, steps):
new_list.append(alist[x * cols: (x + 1) * cols])
new_list[-1].extend([None for t in range(cols - len(new_list[-1]))])
print(new_list)
輸出
[['a', 'b'], ['c', None]]

holdtom
TA貢獻1805條經驗 獲得超10個贊
您可以使用列表理解來實現結果:
li = ['a','b','c']
l = len(li)
new_list = [li[x:x+2] for x in range(l // 2)]
if l % 2 != 0:
new_list.append([li[-1], None])
print(new_list) # [['a', 'b'], ['c', None]]
添加回答
舉報
0/150
提交
取消