2015-09-25 42 views
0
items = {'b': 'Bike', 'm': 'Motorcycle', 'd': 'Dresser', 't': 'Trailer', 'c': 'Car',} 

while True: 
    print "1. Add an item." 
    print "2. Find an item." 
    print "3. Print the message board." 
    print "4. Quit." 
    choice = input("Enter your selection: ") 
    if choice == 1: 
     item = raw_input("Enter the item type-b,m,d,t,c:") 
     cost = raw_input("Enter the item cost:") 
     elts = [] 
     elts.append([items[item],cost]) 
    if choice == 2: 
     itemType = raw_input("Enter the item type=b,m,d,t,c:") 
     itemCost = raw_input("Enter maximum item cost:") 
     if itemType == item and itemCost <= cost: 
      print "Sold ", itemType, "for", itemCost 
    if choice == 3: 
     print str(elts) + ':' 
    if choice == 4: 
     print elts 
     break 

我試圖用添加a來打印str(elts):把它分離出來,但是對於這個不太熟悉,不知道如何以某種方式顯示元素。如何以某種方式打印出一組元素?

回答

1

您每次插入項目時都會創建一個新列表(elts)。

試試這個:

elts = [] # Create the list here 
while True: 
    ... 
    if choice == 1: 
     item = raw_input("Enter the item type-b,m,d,t,c:") 
     cost = raw_input("Enter the item cost:") 
     # And just append the new element 
     # btw, you were appending a list 
     # Perhaps this is what you need 
     elts.append((items[item], cost)) # Append a tuple 
    ... 

然後你就可以用元組的列表中工作,你喜歡的方式:

使用list comprehensions

if choice == 3: 
    print ['{0}:{1}'.format(item, cost) for item, cost in elts] 

使用reduce()

if choice == 3: 
    print reduce(lambda t1, t2: '{0}:{1}, {2}:{3}'.format(t1[0], t1[1], t2[0], t2[1]), elts) 

UPDATE

你也可以用這個解決您的第二個條件:

if any([items[itemType] == i and itemCost <= c for i, c in elts]): 
    print "Sold ", items[itemType], "for", itemCost 
+0

是的,這沒有工作謝謝你,雖然我想打印的項目類型,的格式「:」。 itemCost –

+0

您是否看到使用列表解析@FrankValdez的示例?您可以按照您想要的方式修改每個元組的字符串格式 –

+0

也許您正在嘗試打印每個項目類型的所有成本總和,是正確的嗎? –