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)以分隔它,但是我对此非常新,并且不知道如何以某种方式显示元素。
答案 0 :(得分: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
...
然后你可以按照自己喜欢的方式处理元组列表:
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)
<强>更新强>
你也可以用这个来修复你的第二个条件:
if any([items[itemType] == i and itemCost <= c for i, c in elts]):
print "Sold ", items[itemType], "for", itemCost