Is there any easy way to add elements in lists in a list to make all lists in a list has a same number of element?

拟墨画扇 提交于 2021-02-16 15:26:31

问题


Honestly, I didn't find out for this question cuz... I don't know how to search or google it. So it might be the basic problem, but if anyone can helps me, I would really appreciate it.

So, the problem is... basically from the Index Error: list index out of range, which was raised while I tried to make a list of lists to excel file.

Apparently, the error raised cuz some of my list has 8 elements while some of my list has less elements than those.

for example:

results = [[1,2,3],[1,2,3,4],[1,2,3,4,5,6,7,8]]

and I tried to convert it as excel with xlsxwriter with this code:

for row in range(len(results)):
    for col in range(len(results[0])):
        sheet.write(row, col, results[row][col])

And now you know why the error was raised.

So, what I want to do about it is adding some blank elements to the less-element-having list to make all list has a same number of elements

like this:

results = [[1,2,3,'','','','',''],[1,2,3,4,'','','','',],[1,2,3,4,5,6,7,8]]

Thanks for your attention and helps in advance!


回答1:


Using zip with itertools.zip_longest:

import itertools

list(zip(*itertools.zip_longest(*results, fillvalue='')))

Output:

[(1, 2, 3, '', '', '', '', ''),
 (1, 2, 3, 4, '', '', '', ''),
 (1, 2, 3, 4, 5, 6, 7, 8)]



回答2:


There are many ways to do this, hers's one:

results = [[1,2,3],[1,2,3,4],[1,2,3,4,5,6,7,8]]
m = max(len(l) for l in results)
results = [l + ['']*(m-len(l)) for l in results]



回答3:


Rather than change the data to suit the loop it would be better to change the loop.

The enumerate() function is helpful for this:

import xlsxwriter

workbook = xlsxwriter.Workbook('test.xlsx')
worksheet = workbook.add_worksheet()

results = [[1,2,3],[1,2,3,4],[1,2,3,4,5,6,7,8]]

for row, row_data in enumerate(results):
    for col, data in enumerate(row_data):
        worksheet.write(row, col, data)

workbook.close()

Output:



来源:https://stackoverflow.com/questions/55467635/is-there-any-easy-way-to-add-elements-in-lists-in-a-list-to-make-all-lists-in-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!