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 appreciat
Solution 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)]
Solution 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]
Solution 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:
Post a Comment for "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?"