Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify print function for multiple columns - Python

I'm working on a command line interpreter, and I have a function which prints out a long list of strings in a easy to read manner.

The function is:

def pretty_print(CL_output):
    if len(CL_output)%2 == 0:
        #even
        print "\n".join("%-20s %s"%(CL_output[i],CL_output[i+len(CL_output)/2]) for i in range(len(CL_output)/2))    
    else:
        #odd
        d_odd = CL_output + ['']
        print "\n".join("%-20s %s"%(d_odd[i],d_odd[i+len(d_odd)/2]) for i in range(len(d_odd)/2))

So, for a list such as:

myList = ['one','potato','two','potato','three','potato','four','potato'...]

The function pretty_print returns:

pretty_print(myList)

>>> one                  three
    potato               potato
    two                  four
    potato               potato

However for a larger list, the function pretty_print still prints out the list in two columns. Is there a way to modify pretty_print so that it prints out a list on 3 or 4 columns depending on the size of the list? So len(myList) ~ 100, pretty_print will print out on 3 lines and for len(myList) ~ 300, pretty_print will print out on 4 columns.

So if i have:

  myList_long = ['one','potato','two','potato','three','potato','four','potato'...
           'one hundred`, potato ...... `three hundred`,potato]

The desired output is:

pretty_print(myList_long)

>>> one                  three                one hundred          three hundred
    potato               potato               potato               potato
    two                  four                 ...                  ...
    potato               potato               ...                  ....
like image 672
Holtz Avatar asked Sep 24 '26 14:09

Holtz


1 Answers

Modified from this answer.

def pretty_print(CL_output):
    columns = len(CL_output)//200+2
    lines = ("".join(s.ljust(20) for s in CL_output[i:i+columns-1])+CL_output[i:i+columns][-1] for i in range(0, len(CL_output), columns))
    return "\n".join(lines)
like image 57
Ramchandra Apte Avatar answered Sep 28 '26 22:09

Ramchandra Apte