gpt4 book ai didi

python - 打印字典中的总值

转载 作者:太空宇宙 更新时间:2023-11-03 20:32:45 27 4
gpt4 key购买 nike

我是一名Python初学者,目前正在遵循指南here 。我正在查看第 5 章“嵌套字典和列表”部分中的一段代码。我从代码中删除了一些内容,如下所示:

allGuests = {'Carol': {'cups': 3, 'apple pies': 1}, 'Tom': {'cups': 4, 'juice': 4}}

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

print('Number of things being brought:')
print(' - Cups being brought ' + str(totalBrought(allGuests, 'cups')))

下面是上述代码的输出:

Number of things being brought:
- Cups being brought 3

Process finished with exit code 0

上面的代码应该完成的是打印出 Carol 和 Tom 带来的杯子总数。相反,它只打印出卡罗尔带来的杯子。预期输出应如下所示:

Number of things being brought:
- Cups being brought 7

Process finished with exit code 0

我查看了一个示例 here并亲自尝试过,但这不是我需要的。我试图理解代码的问题以及如何在嵌套字典中正确输出相同的总值。

最佳答案

问题在于 return 语句的缩进:

allGuests = {'Carol': {'cups': 3, 'apple pies': 1}, 'Tom': {'cups': 4, 'juice': 4}}

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

print('Number of things being brought:')
print(' - Cups being brought ' + str(totalBrought(allGuests, 'cups')))

Output:

Number of things being brought:
- Cups being brought 7

关于python - 打印字典中的总值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57380872/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com