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
  • 9,083
  • 4
  • 40
  • 55
Subhashi
  • 4,145
  • 1
  • 23
  • 22

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
  • 114,268
  • 16
  • 167
  • 218