I have this list of lists :
cont_det = [['TASU 117000 0', "TGHU 759933 - 0", 'CSQU3054383', 'BMOU 126 780-0', "HALU 2014 13 3"], ['40HS'], ['Ha2ardous Materials', 'Arm5 Maehinery']]
Practically cont_det is a huge list with lots of sub-lists with irregular length of each sub-list. This is just a sample case for demonstration. I want to get the following output :
[['TASU 117000 0', '40HS', 'Ha2ardous Materials'],
['TGHU 759933 - 0', '40HS', 'Arm5 Maehinery'],
['CSQU3054383', '40HS', 'Ha2ardous Materials'],
['BMOU 126 780-0', '40HS', 'Ha2ardous Materials'],
['HALU 2014 13 3', '40HS', 'Ha2ardous Materials']]
The logic behind this is zip_longest the list of lists but in case there is any sub-list whose length is less than the maximum of all lengths of the sub-lists (which is 5 here for first sub-list), then in stead of default fillvalue=None take the first item of that sub-list - as seen in case of second sub-list all reflected filled values are same and for the third one, the last three are filled by the first value.
I have got the result with this code :
from itertools import zip_longest as zilo
from more_itertools import padded as pad
max_ = len(max(cont_det, key=len))
for i, cont_row in enumerate(cont_det):
if len(cont_det)!=max_:
cont_det[i] = list(pad(cont_row, cont_row[0], max_))
cont_det = list(map(list, list(zilo(*cont_det))))
This gives me the expected result. In stead had I done list(zilo(*cont_det, fillvalue='')) I would have gotten this :
[('TASU 117000 0', '40HS', 'Ha2ardous Materials'),
('TGHU 759933 - 0', '', 'Arm5 Maehinery'),
('CSQU3054383', '', ''),
('BMOU 126 780-0', '', ''),
('HALU 2014 13 3', '', '')]
Is there any other process (like mapping any function or so) to the parameter fillvalue of the zip_longest function so that I don't have to iterate through the list to pad each sub-list up to the length of the longest sub-list before that and this thing can be done in a line with only zip_longest?