简体   繁体   中英

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?

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!

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

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]

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:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM