【发布时间】:2022-06-10 22:47:30
【问题描述】:
我无法操作字典的值。就我的代码而言,我似乎无法让字典显示任何内容,更不用说将 menu 的键分配给 specialMenu 如果任何值是 20 美元或更多。
有人可以帮助显示和解释字典的语法,只显示 $20 或更多的任何值以及如何将它们分配给 specialMenu 字典?
我读入的txt文件信息如下:
Ham and Egg Sandwich $15.75
Bacon and Cheese Plate $9.50
Tuna Salad $12.30
Ceasar Salad $8.00
Beef Soup $9.00
Spicy Beef Barbeque $20.00
Pork Barbeque $18.00
Oven Chicken Barbeque $15.00
Pulled Beef Barbeque Burger $25.00
House Salad $5.00
Turkey Burger $17.00
Mushroom Swiss Burger $15.00
Full Rack of Ribs $22.50
Half Rack of Ribs $11.25
Cheese Cake $9.50
House Tea $3.00
Champagne $20.00
Pellegrino $5.40
White Wine $7.50
Red Wine $11.00
这是我的代码:
menu = {}
specailMenu = {}
def getMenu():
"""Displays the menu.txt file"""
print("Here is our current menu: \n")
inputFile = open("standardMenu.txt", 'r')
print("{:<30} {:<10}".format("Item", "Price"))
for line in inputFile:
itemInfo = line.split("$")
itemName = itemInfo[0].strip()
itemPrice = itemInfo[1].strip()
menu[itemName] = itemPrice
print("{:<30} ${:<10.2f}".format(itemName, float(itemPrice)))
print("\n")
inputFile.close()
getSpecailMenu(menu)
return
def getSpecailMenu(menu):
"""Takes Menu items $20 or more and adds them to Specail Menu"""
#sortedByValue = {k:v for k,v in sorted(menu.items(),key = lambda v:v[1])}
for k,v in menu.items():
if v == 20:
specailMenu.append(k)
print(specailMenu)
"""viewMenu(specailMenu)
print("The total average cost of the Specail Menu is ",mean(specailMenu))"""
return
def viewMenu(specaiMenu):
"""Displays the Menu"""
print("Here is our Specail Menu")
print("{:<30} {:<10}".format("Item", "Price"))
for x, y in specailMenu.items():
print("{:<30} ${:<10.2f}".format(x, float(y)))
def mean(x):
"""find the average of the menu cost"""
total = 0
for count in x:
total += count
return total / len(x)
def ext():
"""exits the program"""
input("Hit any button to exit: ")
exit
return
def main():
"""The main function for this script"""
getMenu()
ext()
if __name__ == "__main__":
main()
【问题讨论】:
-
您不会将价格转换为数字类型。你也想做
if v >= 20。
标签: python