假設你已經有了最大數量的列,並且已經將它們分成了列表(我假設你把它們放到了自己的列表中),你應該可以使用list.insert( - 1,項目)來添加空列:
def columnize(mylists, maxcolumns):
for i in mylists:
while len(i) < maxcolumns:
i.insert(-1,None)
mylists = [["author1","author2","author3","this is the title of the article"],
["author1","author2","this is the title of the article"],
["author1","author2","author3","author4","this is the title of the article"]]
columnize(mylists,5)
print mylists
[['author1', 'author2', 'author3', None, 'this is the title of the article'], ['author1', 'author2', None, None, 'this is the title of the article'], ['author1', 'author2', 'author3', 'author4', 'this is the title of the article']]
不破壞原來的列表,列表解析法替代版本:
def columnize(mylists, maxcolumns):
return [j[:-1]+([None]*(maxcolumns-len(j)))+j[-1:] for j in mylists]
print columnize(mylists,5)
[['author1', 'author2', 'author3', None, 'this is the title of the article'], ['author1', 'author2', None, None, 'this is the title of the article'], ['author1', 'author2', 'author3', 'author4', 'this is the title of the article']]
假設文章標題始終是列表的最後一項,是否安全?另外,你嘗試過什麼方法? –
我有它與變量列數工作,但這不會做。我需要有一定數量的列。我已經建立了列表並嘗試添加到列表中,但我堅持在列表中添加空白項。 – aeupinhere
這是我站在... http://pastebin.com/A2CT97s9 – aeupinhere