Python printing list in columns -


this question has answer here:

how can print in python values list in columns?

i sorted them, don't know how print them in 2 ways 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 want align ljust/rjust.

i tried this:

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

but displays in first example. don't know if proper way this.

the_list = ['apricot','banana','apple','car','coconut','baloon','bubble'] num_columns = 3  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 comprehensive solution addresses both examples have given. have created function , have commented code clear understand being done.

def print_sorted_list(data, rows=0, columns=0, ljust=10):     """     prints sorted item of list data structure formated using     rows , columns parameters     """      if not data:         return      if rows:         # column-wise sorting         # must know number of rows print on each column         # before print next column. since cannot         # move cursor backwards (unless using ncurses library)         # have know each row upfront         # printing rows line line instead         # of printing column column         lines = {}         count, item in enumerate(sorted(data)):             lines.setdefault(count % rows, []).append(item)         key, value in sorted(lines.items()):             item in value:                 print item.ljust(ljust),             print     elif columns:         # row-wise sorting         # need know how many columns should row have         # before print next row on next line.         count, item in enumerate(sorted(data), 1):             print item.ljust(ljust),             if count % columns == 0:                 print     else:         print sorted(data)  # 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) 

Comments

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

angular2 services - Angular 2 RC 4 Http post not firing -