【发布时间】:2020-06-16 09:40:27
【问题描述】:
我从一本名为 Automate The Boring Stuff With Python 的教科书中得到它。我做了很多研究,但仍然无法理解。任何人都可以逐步提供澄清吗?
allGuests = {'Alice': {'apples': 5, 'pretzels': 12},
'Bob': {'ham sandwiches': 3, 'apples': 2},
'Carol': {'cups': 3, 'apple pies': 1}}
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(' - Apples' + str(totalBrought(allGuests, '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')))
输出:
Number of things being brought:
- Apples 7
- Cups 3
- Cakes 0
- Ham Sandwiches 3
- Apple Pies
1
【问题讨论】:
-
由于您还没有做很多研究,请尝试研究 Python 数据结构,尤其是字典,以了解这里发生了什么。例如这里:docs.python.org/2.7/tutorial/datastructures.html#dictionaries Stackoverflow 上还有一个很好的 Python 资源列表,可以帮助您入门,请参阅:stackoverflow.com/tags/python/info
-
你是在 Python 2.x 还是 3.x 下运行这个?
-
我在 python 3.x 中运行这段代码
-
请询问您不理解的单个特定部分。例如,如果是
numBrought = 0行让您感到困惑:它会将值0分配给名为numBrought的变量。如果您需要对每一行进行这样的解释,那么最好从头开始学习 Python。 -
我在打印命令中怀疑它是如何从顶部检索数据的。
标签: python python-3.x python-2.7