我有以下一组代码,但不确定如何对变量进行排序。我查看的所有线程都讨论了排序列表,但我想对变量进行排序,然后按降序打印出来。
print 'Welcome to the Cafe!'
print 'This is our list of items on our small menu'
print ' -------------- Sandwiches -----------------'
print '1 : Grilled Cheese $2.00'
print '2 : Tuna Sandwich $2.00'
print '3 : Chicken Sandwich $2.00'
print ' -------------- Drinks ---------------------'
print '4 : Water $1.00'
print '5 : Soda $1.50'
'6 : Coffee $2.00'
print ' -------------- Salads ---------------------'
print '7 : Chicken Caesar Salad $4.00'
print '8 : Tuna Salad $3.50'
print '9 : House Salad $2.00'
print 'Enter 10 when you are ready to complete your order'
endval = 0
gri = 0
tunas = 0
chics = 0
wat = 0
soda = 0
cof = 0
chic = 0
tuna = 0
hs = 0
inp = 0
total = 0
sandsub = 0
drinksub = 0
salsub = 0
while inp != 10:
inp=raw_input('What would you like to order? ')
if inp=='1':
gri += 1
elif inp=='2':
tunas += 1
elif inp=='3':
chics += 1
elif inp=='4':
wat += 1
elif inp=='5':
soda += 1
elif inp=='6':
cof +=1
elif inp=='7':
chic+=1
elif inp=='8':
tuna +=1
elif inp=='9':
hs +=1
elif inp =='10':
break
else:
print('Invalid Menu Selection')
sandsub = (gri*2) + (tunas*2) + (chics*2)
drinksub = (wat*1) + (soda*1.5) + (cof*2)
salsub = (chic*4) + (tuna*3.5) + (hs*2)
total = (sandsub) + (drinksub) + (salsub)
print '---------- Sandwiches -----------'
print 'You ordered ' ,gri, ' Grilled Cheese'
print 'You ordered ' ,tunas, ' Tuna Salad Sandwiches'
print 'You ordered ' ,chics, ' Chicken Salad Sandwiches'
print 'Your sandwich subtotal comes out to : $%0.2f ' %sandsub
print '---------- Drinks --------------'
print 'You ordered ' ,wat, ' Waters'
print 'You ordered ' ,soda, ' Sodas'
print 'You ordered ' ,cof, ' Coffees'
print 'Your drinks subtotal comes out to : $%0.2f ' %drinksub
print '---------- Salads --------------'
print 'You ordered ' ,chic, ' Chick Salads'
print 'You ordered ' ,tuna, ' Tuna Salads'
print 'You ordered ' ,hs, ' House Salads'
print 'Your salad subtotal comes out to : $%0.2f ' %salsub
print '---------- Grand Total --------------'
print 'Your total comes out to : $%0.2f ' %total
print 'Enjoy your meal and have a nice day!'
答案 0 :(得分:0)
将所有变量放在2元组列表中,然后对列表进行排序
my_sorted_list = sorted([(gri, 'gri'), (tunas, 'tunas'), ...], reverse=True)
for value, name in my_sorted_list:
print name, '=', value
ps:不要像这样使用全局变量,dict对此会很好,它会避免使用if .. elif .. if ... elif .. code