1

How can I print in Python values from list in columns?

I sorted them, but I don't know how to print them in two ways For instance:

list=['apricot','banana','apple','car','coconut','baloon','bubble']

First one:

apricot      bubble     ...
apple        car        
baloon       coconut

Second way:

apricot    apple     baloon   
bubble     car      coconut

I also want to align everything with ljust/rjust.

I tried something like this:

print " ".join(word.ljust(8) for word in list)

but it displays only like in first example. I don't know if it is proper way to do this.

idjaw
  • 21,992
  • 6
  • 53
  • 69
Knight
  • 451
  • 1
  • 6
  • 20

1 Answers1

2
the_list = ['apricot','banana','apple','car','coconut','baloon','bubble']
num_columns = 3

for count, item in enumerate(sorted(the_list), 1):
    print item.ljust(10),
    if count % num_columns == 0:
        print

output:

apple      apricot    baloon    
banana     bubble     car       
coconut

UPDATE: Here is the comprehensive solution that addresses both examples you have given. I have created a function for this and i have commented the code so that its clear to understand what it is being done.

def print_sorted_list(data, rows=0, columns=0, ljust=10):
    """
    Prints sorted item of the list data structure formated using
    the rows and columns parameters
    """

    if not data:
        return

    if rows:
        # column-wise sorting
        # we must know the number of rows to print on each column
        # before we print the next column. But since we cannot
        # move the cursor backwards (unless using ncurses library)
        # we have to know what each row with look like upfront
        # so we are basically printing the rows line by line instead
        # of printing column by column
        lines = {}
        for count, item in enumerate(sorted(data)):
            lines.setdefault(count % rows, []).append(item)
        for key, value in sorted(lines.items()):
            for item in value:
                print item.ljust(ljust),
            print
    elif columns:
        # row-wise sorting
        # we just need to know how many columns should a row have
        # before we print the next row on the next line.
        for count, item in enumerate(sorted(data), 1):
            print item.ljust(ljust),
            if count % columns == 0:
                print
    else:
        print sorted(data)  # the default print behaviour


if __name__ == '__main__':
    the_list = ['apricot','banana','apple','car','coconut','baloon','bubble']
    print_sorted_list(the_list)
    print_sorted_list(the_list, rows=3)
    print_sorted_list(the_list, columns=3)
dopstar
  • 1,406
  • 10
  • 20
  • Thanks a lot :) Could you tell me, if there is a way to print it like i have shown in first example? – Knight Nov 01 '15 at 16:11
  • 1
    @bartekshadow I have updated my answer to include a solution that also cater for your first example. – dopstar Nov 01 '15 at 17:03