2015-05-02 84 views
2

我是python的新手,想用python创建比萨订购系统,看起来像这样。用python创建餐厅/比萨菜单,并且布局良好

1 Hawaiian      $7.50 
2 Champagne Ham & Cheese  $7.50 
3 Beef & Onion     $7.50 
4 Pepperoni      $7.50 
5 Simply Cheese     $7.50 
6 Bacon & Mushroom    $7.50 
7 Italiano      $7.50 
8 The Deluxe     $13.50 
9 Ham, Egg & Hollandaise  $13.50 
10 Americano      $13.50 
11 Mr Wedge      $13.50 
12 BBQ Meatlovers    $13.50 

我然后像客户能够选择,基于数不同的比萨饼,使他们不必键入夏威夷,他们可以代替1型 我曾经尝试都字典和列表,但总是导致了这个问题:

1 Hawaiian $7.50 
2 Champagne Ham & Cheese$7.50 
3 Beef & Onion $7.50 
4 Pepperoni $7.50 
5 Simply Cheese $7.50 
6 Bacon & Mushroom $7.50 
7 Italiano $7.50 
8 The Deluxe $13.50 
9 Ham, Egg & Hollandaise $13.50 
10 Americano $13.50 
11 Mr Wedge $13.50 
12 BBQ Meatlovers $13.50 

当价格将“坚持比萨饼名”和比萨饼月10日起由一个字符缩进的名字。手动放置空间似乎不是解决我的问题的最有效方式。例如

standardprice = "$7.50" 
    deluxeprice = "13.50" 
    print (
    """ 
1 Hawaiian      %s 
2 Champagne Ham & Cheese  %s 
3 Beef & Onion     %s 
4 Pepperoni      %s 
5 Simply Cheese     %s 
6 Bacon & Mushroom    %s 
7 Italiano      %s 
8 The Deluxe     %s 
9 Ham, Egg & Hollandaise  %s 
10 Americano      %s 
11 Mr Wedge      %s 
12 BBQ Meatlovers    %s 
    """ % (standardprice, standardprice, standardprice, standardprice, 
      standardprice, standardprice, standardprice,deluxeprice,    
      deluxeprice,deluxeprice, deluxeprice, deluxeprice) 
     ) 

有没有更简单的方法来解决我的问题?在打印时,作为一个侧面问题,“标准价格”变量适用于前7个元素,而豪华价格适用于8-12,而不是我已经完成的粗糙方式。

here有一个类似的问题,但该网页并没有帮助。 Code Academies “在超市教程的一天”也不是特别有用。 我对python很陌生,所以像我知道的一样解释会很有帮助

+0

如果没有[spam](http://www.detritus.org/spam/skit.html),您无法在Python中创建餐厅菜单! – abarnert

+0

同时,“我已经尝试过两本字典和列表”并不能帮助我们,除非你向我们展示了你的尝试。这个问题当然可以用字典或列表来解决;如果你弄错了,并希望我们帮助你,我们需要看到你试图解释你错了什么,以及如何解决它。 – abarnert

+0

http://stackoverflow.com/questions/5676646/fill-out-a-python-string-with-spaces – dbliss

回答

1

有一些super handy utilities字符串格式化:ljust | rjust,对于只是这样的事情。

下面是一个简单的例子,我用ljust鞭打过,但不要停在这里;看一下上面链接的文档,让您的想象力随着字符串格式自由而疯狂!

from collections import namedtuple 

MenuEntry = namedtuple('MenuEntry', ['index','description','price']) 
_menu = [] 
_menu.append(MenuEntry(1, 'Hawaiian', '$7.50')) 
_menu.append(MenuEntry(2, 'Champagne Ham & Cheese', '$7.50')) 
_menu.append(MenuEntry(3, 'Beef & Onion', '$7.50')) 
_menu.append(MenuEntry(40, 'Pepperoni', '$10.50')) 
_menu.append(MenuEntry(100, 'Simply Cheese', '$17.50')) 

for entry in _menu: 
    index = str(getattr(entry,'index')).ljust(5) 
    descr = getattr(entry,'description').ljust(25) 
    price = getattr(entry,'price').ljust(7) 
    print '{0}{1}{2}'.format(index,descr,price) 

""" Output: """ 

1 Hawaiian     $7.50 
2 Champagne Ham & Cheese $7.50 
3 Beef & Onion    $7.50 
40 Pepperoni    $10.50 
100 Simply Cheese   $17.50 

"""""""""""""""""""""""""""" 
+1

为什么你使用'getattr(entry,'index')'而不是'entry.index'? – abarnert

+0

另外,如果你打算最终使用'str.format',为什么不直接在格式字符串中使用对齐方式,而是在4行内分两步进行呢? (然后你也不需要'str'调用来启动。) – abarnert

+1

谢谢,这种方法最适合我的问题。我想如果你能回答abarnert关于进一步改进代码的评论。对于下一步,用户选择他们想要的食物,如果你有空闲时间,并希望进一步加强我的工作,那将会很棒,但同时我会自己完成。 @MrDuk – afro

-1

这是一个快速和肮脏的版本,你当然应该做一些检查,以避免错误。但是,这将工作:

from collections import OrderedDict 

thatsALowPrice = 7.50 
thatsAHighPrice = 10.50 

myMenu = OrderedDict() 

myMenu["Sandwich"] = thatsALowPrice 
myMenu["Burger"] = thatsALowPrice 
myMenu["Steak"] = thatsAHighPrice 

i=1 
for k, v in myMenu.items(): 
    print(i, ":", k, "\t\t", v) 
    i+=1 

itemNumber = int(input("Choose your item: ")) 
item=list(myMenu.items())[itemNumber-1] 

print("You chose", item[0], "at a price of: $"+str(item[1])) 
+1

不仅这是快速和肮脏的,它直接不能完成OP所要求的。 – dbliss

+1

@dbliss:但从好的一面来说,它确保使用制表符,以便在不同的终端上以不同的方式完成它。 – abarnert

0

这里的工作的例子,但是我用了pandas库对自己节省大量的悲痛。如果可以/想要先通过评论,如果还有其他问题,请回过头来。

不可否认,这不适合初学者,但除了DataFrame的格式部分外,它非常基本。

import pandas as pd 

pizzas = [ 
    "Hawaiian", 
    "Champagne Ham & Cheese", 
    "Beef & Onion", 
    "Pepperoni", 
    "Simply Cheese", 
    "Bacon & Mushroom", 
    "Italiano", 
    "The Deluxe", 
    "Ham, Egg & Hollandaise", 
    "Americano", 
    "Mr Wedge", 
    "BBQ Meatlovers" 
    ] 

df = pd.DataFrame(pizzas, columns=["Pizzas"]) 
df.loc[:8, "Prices"] = 7.50  # First 7 items. 
df.loc[8:, "Prices"] = 13.50 # All the rest. 
df.index += 1     # So that it's not zero-indexed. 
total_bill = 0.0    # Meh. 

print "Welcome to Pizza Planet!" # So unoriginal, I know. 
print 
print "Here's our menu!" 
print 
# Following method taken and modified from unutbu's amazing answer 
# here: http://stackoverflow.com/questions/25777037 
print df.to_string(justify='left', 
        header=False, 
        formatters={ 
        'Pizzas':'{{:<{}s}}'.format(
         df['Pizzas'].str.len().max() 
         ).format, 
        'Prices':'  ${:.2f}'.format}) 
print 
print "Input a number and press enter to select an item." 
print "Input 'done' to finish your order and tabulate your bill." 
print "Input 'exit' to cancel your orders." 

while True: 

    order = raw_input(">>> ") 

    if order == 'exit': 
     break 
    elif order == 'done': 
     print "Your total bill is ${:.2f}.".format(total_bill) 
     raw_input("Press any key to exit.") 
     break 
    elif int(order) in df.index: 
     item = df.loc[int(order), "Pizzas"]  # Get the respective items 
     price = df.loc[int(order), "Prices"] # by indexing order input. 
     print "You've selected {}! That would be ${:.2f}.".format(item, price) 
     total_bill += price 
     continue 
    else: 
     print "Don't be an idiot." # :-) 
     raw_input("Press any key to exit.") 
     break 

结果:

enter image description here