GSujiKanth
GSujiKanth

Reputation: 1

How to print two columns with different range using for loops?

I need some very basic help with Python. I'm trying to get a better understanding of formatting using a for loop and I want to print out vertical Histogram.

Here is what I've tried:

tot_progress = 2
tot_trailer = 4
tot_retriever = 3
tot_exclude = 4
# Vertical Histogram
print("Progress", " Trailing", " Retriever", " Excluded")
a = '*'
for i,j,k,l in zip(range(0, tot_progress, 1), range(0, tot_trailer, 1), range(0, tot_retriever, 1), range(0, tot_exclude, 1)):
    print('{}\t\t\t{}\t\t\t{}\t\t\t{}'.format(a, a, a, a))

The output I got:

Progress  Trailing  Retriever  Excluded
   *         *          *         *
   *         *          *         *

what I want:

Progress  Trailing  Retriever  Excluded
   *         *          *         *
   *         *          *         *
             *          *         *
             *                    *

Upvotes: 0

Views: 218

Answers (2)

cards
cards

Reputation: 4965

In order to have vertical histograms you can format each row to have the same "length" and then zip, so that you can transpose it properly. Used string formatting layout, see here for details.

Each bar of the histogram will be centered wrt to the label of the column.

col_labels = {'Progress statussss': 2, "Trailing": 8, "Retriever": 3, "Excluded": 4}

SYMBOL = '*'
PADDING = 2 # add extra space between two columns

col_sizes = list(map(len, col_labels))

row_template = [(('{S:^' + f'{size + PADDING}' + '}' + ' ') *v)[:-1].split() + [' ' * (size+PADDING) ]*(size - v) for size, v in zip(col_sizes, col_labels.values())]

# column names
print(''.join(('{:^' + f'{col_sizes[i] + PADDING}' + '}').format(v) for i, v in enumerate(col_labels)))
# bars
for l in (''.join(i)  for i in zip(*row_template)):
    print(l.format(S=SYMBOL))

Output

 Progress statussss  Trailing  Retriever  Excluded 
         *              *          *         *     
         *              *          *         *     
                        *          *         *     
                        *                    *     
                        *                          
                        *                          
                        *                          
                        *                                      

Upvotes: 0

Tanmay Shrivastava
Tanmay Shrivastava

Reputation: 579

User itertools longest to iterate to maximum and update your loop with conditions and print accordingly

import itertools

for i,j,k,l in itertools.zip_longest(range(0, tot_progress, 1), range(0, tot_trailer, 1), range(0, tot_retriever, 1), range(0, tot_exclude, 1)):
    ai="*" if not i == None else " "
    aj="*" if not j == None else " "
    ak="*" if not k == None else " "
    al="*" if not l == None else " "
    print('{}\t\t\t{}\t\t\t{}\t\t\t{}'.format(ai, aj, ak, al))

Upvotes: 1

Related Questions