0

I have a array of arrays where each internal array is a variable size, and will change with each run. e.g.:

a = [[T1], [4, 5, 6], ['a', 'b']]

What I'd like to do is print this as a table, with the 1st array as col_1, 2nd col_2, and then col_3. Currently, there will only be 3 cols. Desired result:

COL1     COL2     COL3
----     ----     ----
T1       4        a
         5        b
         6      

I guess I have two major questions:
1. Can this be done
2. How to account for the diff sizes of each array - not in terms of formatting, but looping through elements where there might not be one.

Thanks very much.

p.s. I'm currently experimenting with zip() as that looks like it could work, but still have a mis-matched number of elements in each array.

2 Answers 2

2

You're on the right track with zip. To fill in something where there's nothing, use itertools.zip_longest (in python 2, izip_longest):

for line in zip_longest(*a,fillvalue=''):
    print('\t'.join(map(str,line)))

T1      4       a
        5       b
        6       
Sign up to request clarification or add additional context in comments.

Comments

2

I'm currently experimenting with zip() as that looks like it could work, but still have a mis-matched number of elements in each array.

Yes, as the docs say, zip stops as soon as any of the arrays stops.

But the itertools module has a function called zip_longest (or izip_longest, in 2.x) that solves this problem.

You just need specify what you want as the fill value—in this case, probably '':

for row in itertools.zip_longest(*a, fillvalue=''):
    print('\t'.join(row))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.