I have been working on combining lists of lists...testing answers to various questions on zip, zip_longest, lists, list comprehensions, iteration through lists of unequal lengths lists of lists, but I have been unable to find one that fixes my issue. I am now defeated.
This may very well be a result of my inexperience, but I've run out of places to look.
I have two lists of lists with the internal lists having various lengths.
I want to zip_longest each internal list with the following type of result: [('1', '1. A method'), ('2', '2. The method'), ('Description', '3.Description'), etc.]
The attempts shown below get me results I like but the code generats cross combining of list_1[0] with list_2[1]. I want only combining of lists at the same index (list_1[0] with list_2[0]) then 1:1, 2:2.
from itertools import zip_longest
claim_text = [['1. A method', '2. The method', '3. Description'],
['1. A method', '2. The method', '3. The method', '5. The method']];
claim_num = [['1', '2'], ['1', '2', '3']]
combined = []
for i in claim_text:
for x in claim_num:
combined.append(list(itertools.zip_longest(x,i, fillvalue='Description')))
print(combined)
another approach:
[(list(itertools.zip_longest(a,b, fillvalue='Description'))) for a in claim_num for b in claim_text]
Any help is appreciated.
CodePudding user response:
Do you want to zip_longest
the first num with the first text, second null with second text, etc.?
Then start by combining the sublists of the two inputs with zip
:
[list(zip_longest(a, b, fillvalue='Description'))
for a, b in zip(claim_num, claim_text)]
Output:
[[('1', '1. A method'),
('2', '2. The method'),
('Description', '3. Description')],
[('1', '1. A method'),
('2', '2. The method'),
('3', '3. The method'),
('Description', '5. The method')]]