Home > front end >  Print several arrays as columns
Print several arrays as columns

Time:10-19

I am trying to print a list of arrays where each array is a column. I have the following arrays:

cat=['aba','vdv']
dog=['tul','baba']

I can accomplish what I want by doing the following:

for x in zip(cat,dog):
    print '\t'.join(x)

aba tul
vdv baba

But this is cumbersome if I want to add many more columns, so I'd like to be able to set cat and dog to a single variable and then iterate over that variable, and print out each array as a column in a table like this:

cat=['aba','vdv']
dog=['tul','baba']
df=[cat,dog]

for x in zip(df):
    print '\t'.join(x)

However that produces an error. Any suggestions would be greatly appreciated.

CodePudding user response:

zip receives every iterable as a separate argument, not as a list of arguments. By using zip(df) <=> zip([cat, dog]) you are passing all the iterables as one argument (in the list). Compare:

zip(cat, dog)  # the correct way
zip([cat, dog])  # what you are doing

In the first case, x would have these values during each of the iterations:

  1. ('aba', 'tul',)
  2. ('vdv', 'baba')

In the second case:

  1. (['aba', 'vdv'],)
  2. (['tul', 'baba'],)

To pass every item of the list as a separate argument, you have to unpack the list into separate arguments:

cat = ['aba', 'vdv']
dog = ['tul', 'baba']
df = [cat, dog]

for x in zip(*df):
    print('\t'.join(x))  # using Python 3, so added parenthesis

CodePudding user response:

You were almost there, just missing the unpacking in your call to zip.

cat = ['aba', 'vdv']
dog = ['tul', 'baba']
df = [cat, dog]

for x in zip(*df):
    print('\t'.join(x))

You could also do it without a for loop, like this:

print(*map('\t'.join,zip(*df)),sep='\n')
  • Related