Albert
Albert

Reputation: 13

How to print multiple "for loops" on the same line?

I have this code.

item = stock.stock_list(location)        

for lists in sorted(item):
    print ("{:<20}".format(lists))

for price in sorted(item): 
    print("{:>8.2f}".format(stock_price(price)))

for qty in sorted(item): 
    print("{:>6}".format(stock.stock_quantity(location, qty))

and it prints out,

Beetroot            
Black-eyed peas     
Cassava             
Greater plantain    
Pak choy           
17.03
11.98
11.61
10.09
92
94
76
67

i need it to print out on the same line, like so.

Beetroot             17.03       94
Black-eyed peas      11.98       92
Cassava              43.21       76
Greater plantain     12.45       43
Pak choy             19.22       43

don't worry about the numbers. and it has to be aligned like so,

  "{:<20}{:>8.2f}{:>6}".format

Upvotes: 0

Views: 533

Answers (2)

kdopen
kdopen

Reputation: 8215

Just use one loop:

for i in sorted(item):
    print("{:<20}{:>8.2f}{:>6}".format(i, 
                                       stock_price(i), 
                                       stock.stock_quantity(location, i))

You probably want a better name than i but this is just whiteboard code

Upvotes: 3

Marcin
Marcin

Reputation: 238847

I think is is what you are after (dummy code):

import random

item = ['Beetroot',           
   'Black-eyed peas',   
   'Cassava',           
   'Greater plantain'    
   'Pak choy']


for an_item in sorted(item):
    stoc_price     = random.randint(1,10)
    stock_quantity = random.randint(1,10)
    print("{:<30}{:>8.2f}{:>6}".format(an_item, stoc_price, stock_quantity))

Gives:

Beetroot                          5.00     1
Black-eyed peas                   2.00     8
Cassava                           1.00     5
Greater plantainPak choy          6.00     9

Upvotes: 1

Related Questions