如何在字典中打印递增顺序?

2024-05-19 02:37:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我的程序是一个卡路里计数器,它从一个文本文件中读取食物和卡路里,以及名字+人们吃的食物。在程序结束时,它应该输出名称+总热量(从最低开始)。输出值打印正确,但顺序不正确。你知道吗

有人知道为什么会这样吗?你知道吗

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

Tags: inforsystotaljoepiemaryfoods
1条回答
网友
1楼 · 发布于 2024-05-19 02:37:54

在代码的最后一条语句中,使用列表.append((姓名,总热量))。 稍后定义第二个函数 定义秒(elem): 返回元素[1] 并使用 l、 排序(key=takeSecond) 现在你可以得到你想要的结果了。你知道吗

相关问题 更多 >

    热门问题