我的程序是一个卡路里计数器,它从文本文件以及该人吃的食物的名称和食物中读取食物和卡路里。在程序结束时,它应该输出名称+总卡路里(从最低的开始)。输出值打印正确,尽管顺序不正确。
有人知道为什么会这样吗?
import sys
file = "foods.txt"
line = sys.stdin
fridge = {}
with open(file, "r") as f:
for a in f:
a = a.strip().split()
food = " ".join(a[:-1])
calorie = a[-1]
fridge[food] = calorie
for i in line:
i = i.strip().split(",")
name = i[0]
foods = i[1:]
total_calories = 0
for k in foods:
calorie = fridge.get(k)
if k in fridge:
total_calories += int(calorie)
print("{} : {}".format(name, total_calories))
#My_Output
#joe : 2375
#mary : 785
#sandy : 2086
#trudy : 875
#Expected_Output
#trudy : 875
#mary : 985
#sandy : 2186
#joe : 2375
#foods.txt
#almonds 795
#apple pie 405
#asparagus 15
#avocdo 340
#banana 105
#blackberries 75
#blue cheese 100
#blueberries 80
#muffin 135
#blueberry pie 380
#broccoli 40
#butter 100
#cabbage 15
#carrot cake 385
#cheddar cheese 115
#cheeseburger 525
#cherry pie 410
#chicken noodle soup 75
#chocolate chip cookie 185
#cola 160
#cranberry juice 145
#croissant 235
#danish pastry 235
#egg 75
#grapefruit juice 95
#ice cream 375
#lamb 315
#lemon meringue pie 355
#lettuce 5
#macadamia nuts 960
#mayonnaise 100
#mixed grain bread 65
#orange juice 110
#potatoes 120
#pumpkin pie 320
#rice 230
#salmon 150
#spaghetti 190
#spinach 55
#strawberries 45
#taco 195
#tomatoes 25
#tuna 135
#veal 230
#waffles 205
#watermelon 50
#white bread 65
#wine 75
#yogurt 230
#zuchini 16
#sys.stdin
#joe,almonds,almonds,blue cheese,cabbage,mayonnaise,cherry pie,cola
#mary,apple pie,avocado,broccoli,butter,danish pastry,lettuce,apple
#sandy,zuchini,yogurt,veal,tuna,taco,pumpkin pie,macadamia nuts,brazil nuts
#trudy,waffles,waffles,waffles,chicken noodle soup,chocolate chip cookie
答案 0 :(得分:0)
在代码的最后一条语句中,而不是将值打印到使用 list.append((name,totalcalories))预定义的列表中。 稍后定义takeSecond函数 def takeSecond(elem): 返回elem [1] 并使用 l.sort(key = takeSecond) 现在您可以得到所需的结果。