Skip to main content
added 194 characters in body
Source Link
Sigur
  • 295
  • 1
  • 2
  • 10

Here is my proposal. It is shorter than OP's solution, specially to compute the length of each word to be used in the format procedure while printing.

In a single line, we obtain a 1D array with maximal lengths.

import numpy as np

tableData = [['apples', 'oranges', 'cherries', 'banana'],
             ['Alice', 'Bob', 'Carol', 'David'],
             ['dogs', 'cats', 'moose', 'goose']]

max_len = np.array([np.array(max([len(xii) for xii in xi])) for xi in tableData])

for col in range(len(tableData[0])):
    for i in range(len(tableData)):
        print ("{:>%d}" % max_len[i]).format(tableData[i][col]),
    print ""

Output

  apples Alice  dogs 
 oranges   Bob  cats 
cherries Carol moose 
  banana David goose

Here is my proposal.

import numpy as np

tableData = [['apples', 'oranges', 'cherries', 'banana'],
             ['Alice', 'Bob', 'Carol', 'David'],
             ['dogs', 'cats', 'moose', 'goose']]

max_len = np.array([np.array(max([len(xii) for xii in xi])) for xi in tableData])

for col in range(len(tableData[0])):
    for i in range(len(tableData)):
        print ("{:>%d}" % max_len[i]).format(tableData[i][col]),
    print ""

Output

  apples Alice  dogs 
 oranges   Bob  cats 
cherries Carol moose 
  banana David goose

Here is my proposal. It is shorter than OP's solution, specially to compute the length of each word to be used in the format procedure while printing.

In a single line, we obtain a 1D array with maximal lengths.

import numpy as np

tableData = [['apples', 'oranges', 'cherries', 'banana'],
             ['Alice', 'Bob', 'Carol', 'David'],
             ['dogs', 'cats', 'moose', 'goose']]

max_len = np.array([np.array(max([len(xii) for xii in xi])) for xi in tableData])

for col in range(len(tableData[0])):
    for i in range(len(tableData)):
        print ("{:>%d}" % max_len[i]).format(tableData[i][col]),
    print ""

Output

  apples Alice  dogs 
 oranges   Bob  cats 
cherries Carol moose 
  banana David goose
Source Link
Sigur
  • 295
  • 1
  • 2
  • 10

Here is my proposal.

import numpy as np

tableData = [['apples', 'oranges', 'cherries', 'banana'],
             ['Alice', 'Bob', 'Carol', 'David'],
             ['dogs', 'cats', 'moose', 'goose']]

max_len = np.array([np.array(max([len(xii) for xii in xi])) for xi in tableData])

for col in range(len(tableData[0])):
    for i in range(len(tableData)):
        print ("{:>%d}" % max_len[i]).format(tableData[i][col]),
    print ""

Output

  apples Alice  dogs 
 oranges   Bob  cats 
cherries Carol moose 
  banana David goose