0

I have an array like this:

arr = [['a', 'b', 'c', 'd'],
       ['e', 'f', 'g', 'h'],
       ['i', 'j']]

How to get the output like this?

str = aei bfj cg dh

So basically, how to print a jagged array vertically?

funnydman
  • 4,408
  • 3
  • 22
  • 42
Subhashi
  • 3,899
  • 1
  • 21
  • 21

2 Answers2

4
from itertools import zip_longest
for row in zip_longest(*arr, fillvalue=''):
    print(' '.join(row))
3

You can use itertools.zip_longest to stride column-wise, and then filter out when None is encountered. Then pass that as a generator expression through str.join to create a single space-delimited string.

>>> import itertools
>>> ' '.join(''.join(filter(None, i)) for i in itertools.zip_longest(*arr))
'aei bfj cg dh'
Cory Kramer
  • 107,498
  • 14
  • 145
  • 201