第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

Python 重塑具有奇數(shù)個(gè)元素的列表

Python 重塑具有奇數(shù)個(gè)元素的列表

白豬掌柜的 2023-10-18 21:35:07
我有一個(gè)包含奇數(shù)個(gè)元素的列表。我想把它轉(zhuǎn)換成特定的尺寸。我的代碼: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)當(dāng)前輸出:ValueError: cannot reshape array of size 1 into shape (2,2)預(yù)期輸出:anarray  = [['a','b'],['c',nan]]
查看完整描述

3 回答

?
翻翻過(guò)去那場(chǎng)雪

TA貢獻(xiàn)2065條經(jīng)驗(yàn) 獲得超14個(gè)贊

你可以試試:

out = np.full((rows,cols), np.nan, dtype='object')

out.ravel()[:len(alist)] = alist

輸出:

array([['a', 'b'],
       ['c', nan]], dtype=object)

作為旁注,這可能對(duì)您更好:

rows = int(np.ceil(len(alist)/cols))


查看完整回答
反對(duì) 回復(fù) 2023-10-18
?
Qyouu

TA貢獻(xiàn)1786條經(jīng)驗(yàn) 獲得超11個(gè)贊

嘗試(沒(méi)有任何外部庫(kù))


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]]


查看完整回答
反對(duì) 回復(fù) 2023-10-18
?
holdtom

TA貢獻(xiàn)1805條經(jīng)驗(yàn) 獲得超10個(gè)贊

您可以使用列表理解來(lái)實(shí)現(xiàn)結(jié)果:


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]]


查看完整回答
反對(duì) 回復(fù) 2023-10-18
  • 3 回答
  • 0 關(guān)注
  • 178 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)