Printing elements from multiple lists as a combined line

Nauman Shahid Source

I have combined the data from multiple files into a list of lists. Where each individual list represents the lines found in the file.

Final_List = [['line1', 'line2', 'line3'], ['line1', 'line2', 'line3'], ['line1', 'line2', 'line3', 'line4']]

What I would like to do is cycle through the list and combine the individual lines together (with tab spacing) and print them.

So something like this:

new_line_ 1 = line1\tline1\tline1
new_line_4 = \t\tline4

So essentially, get the first element of the first list and combine it with the first element of the second list, separated by tab, and so forth. However, if one list is bigger than the other - add \t for the missing lines for the other lists.

What's the best way to approach this?

I was thinking of changing the first two lists and adding \t to every element and adding extra \t to make them the same size as list3.

But I feel like there should be a better way to do this.



answered 5 days ago Bubble Bubble Bubble Gut #1

itertools.zip_longest does the trick!

result = itertools.zip_longest(*Final_List, fillvalue='\t')
# result is a generator
result = ['\t'.join(r) for r in result]

comments powered by Disqus