两个字典中的python结果不同

2024-06-02 10:40:58 发布

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

我不明白为什么相同的方法对一个函数和字典有效,而对第二个函数无效,尽管我只是“复制”了它。在

allGuests = {"Alice": {"apples": 5, "pretzels": 12}, "Bob": {"ham sandwiches": 3, "apples": 2}, "Carol": {"cups": 3, "apple pies": 1}}
allCalories = {"apples": {"Calories": 100, "fat": 10}, "pretzels": {"Calories": 200, "fat": 20}, "ham sandwiches": {"Calories": 300, "fat": 30}, "cups": {"Calories": 0, "fat": 0}, "apple pies": {"Calories": 500, "fat": 50}}

def totalBrought(guests, item): 
    numBrought = 0              
    for k, v in guests.items(): 


        numBrought = numBrought + v.get(item, 0) 
    return numBrought

def totalCalories(dish, calories):
    cal = 0
    for k, v in dish.items():
        cal = cal + v.get(calories, 0)
    return cal

print(" Number of Things being brought: ")
print(" - Apples " + str(totalBrought(allGuests, "apples")))
print(" Calories of apples " + str(totalCalories(allCalories, "apples")))
print(" - Cups " + str(totalBrought(allGuests, "cups")))    
print(" - Cakes " + str(totalBrought(allGuests, "cakes")))
print(" - Ham Sandwiches " + str(totalBrought(allGuests, "ham sandwiches")))
print(" - Apple Pies " + str(totalBrought(allGuests, "apple pies")))

结果(错误的)是:

^{pr2}$

有人能解释一下为什么它不起作用吗?对于python初学者来说,这似乎是一个简单的逻辑鸿沟。。。。 提前谢谢!在


Tags: 函数applefatcalhamprintstrcups
3条回答

谢谢你的帮助。为了更好的理解,我改变了名称(见下文)。 可能会有更复杂的解决方案,但我喜欢坚持“初始”的方法,因为我还是个初学者,不想跳过主题,只想采用更复杂的方法。在

^{1}$

然后举例来说:

^{pr2}$

我还添加了其他几行,结果如下:

Number, Calories and Fat of Things being brought: 
- Apples 7
-> Total Calories of Apples 560
-> Total Fat of Apples 14 Gramm
- Pretzels 12
-> Total Calories of Pretzels 2400
-> Total Fat of Pretzels 240 Gramm
- Cups 3
-> Total Calories of Cups 0
-> Total Fat of Cups 0 Gramm
- Cakes 0
-> Total Calories of Cakes 0
-> Total Fat of Cakes 0 Gramm
- Ham Sandwiches 3
-> Total Calories of Ham Sandwiches 900
-> Total Fat of Ham Sandwiches 90 Gramm
- Apple Pies 3
-> Total Calories of Apple Pies 1500
-> Total Fat of Apple Pies 150 Gramm
==>> Total Calories of Things being brought: 5360
==>> Total Fat of Things being brought: 494

错误就在这里:

^{1}$

通过循环,依次迭代每个项,如{"Calories": 100, "fat": 10}{"Calories": 200, "fat": 20},依此类推。但您要查询的是不存在的'apples',并继续添加0。在

你已经拿到钥匙了!您不需要再次迭代dict。这违背了它的目的。在

您只需:

^{pr2}$

我相信你把变量的名字弄错了,这让你很困惑。试试这个:

def totalCalories(calorie_dict, item):
    return calorie_dict[item]["Calories"]

这似乎也是使用Collections模块中的Counter对象的好用例。它允许您在一个调用中计算各种食物的所有频率,而不是要求每个食物单独调用一个函数。在

^{1}$

相关问题 更多 >