4 回答

TA貢獻(xiàn)1886條經(jīng)驗(yàn) 獲得超2個(gè)贊
這是在 itertools(在 python3 中)中提供的,用于迭代,帶有 zip_longest,您可以使用 zip(*) 正常反轉(zhuǎn)它,如果您更喜歡它而不是迭代器,則將其傳遞給列表。
import itertools
from pprint import pprint
sents = [["Hello","World"],["Where","are","you"],["I","am","doing","fine"]]
pad_token = "Hi"
padded = zip(*itertools.zip_longest(*sents, fillvalue=pad_token))
pprint (list(padded))
[['Hello', 'World', 'Hi', 'Hi'],
['Where', 'are', 'you', 'Hi'],
['I', 'am', 'doing', '美好的']]

TA貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超4個(gè)贊
以下是如何使用str.ljust()填充每個(gè)字符串,并使用max()keylen來查找填充每個(gè)字符串的數(shù)字:
lst = ['Hello World', 'Good day!', 'How are you?']
l = len(max(lst, key=len)) # The length of the longest sentence
lst = [s.ljust(l) for s in lst] # Pad each sentence with l
print(lst)
輸出:
['Hello World ',
'Good day! ',
'How are you?']

TA貢獻(xiàn)1811條經(jīng)驗(yàn) 獲得超4個(gè)贊
假設(shè):
輸出應(yīng)與 OP 輸出相同(即每個(gè)子列表中的單詞數(shù)相同)。
輸入:
sents = [["Hello","World"],["Where","are","you"],["I","am","doing","fine"]]
pad_token = "Hi"
以下 1-liner 產(chǎn)生與 OP 代碼相同的輸出。
sents_padded = [sent + [pad_token]*(max_length - len(sent)) for sent in sents]
print(sents_padded)
# [['Hello', 'World', 'Hi', 'Hi'], ['Where', 'are', 'you', 'Hi'], ['I', 'am', 'doing', 'fine']

TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超3個(gè)贊
當(dāng)我計(jì)時(shí)時(shí),這似乎更快:
maxi = 0
for sent in sents:
if sent.__len__() > maxi:
maxi = sent.__len__()
for sent in sents:
while sent.__len__() < maxi:
sent.append(pad_token)
print(sents)
添加回答
舉報(bào)