python - 来自 Automate Boring Stuff With Python 的任务。5
问题描述
我是学习 Python 的新手,阅读的是 Albert Sweigart 的书Automate Boring Stuff With Python。
inventory = {'arrows': 12, 'gold coins': 42, 'rope': 1, 'torches': 6, 'dagger': 1}
从这本字典中,我需要像这样输出:
Inventory:
12 arrows
42 gold coins
1 rope
6 torches
1 dagger
Total number of items: 62
到目前为止,我做了这样的事情,并尝试使用书中的方法:
inventory = {'arrows': 12, 'gold coins': 42, 'rope': 1, 'torches': 6, 'dagger': 1}
def displayInventory(inventory):
totalNum = 0
for k, v in inventory.items():
print(v, k)
totalNum = totalNum + sum(inventory.values())
print("Total items of inventory: ")
return totalNum
print("Your inventory: ")
print(displayInventory(inventory))
输出:
Your inventory:
12 arrows
42 gold coins
1 rope
6 torches
1 dagger
Total items of inventory:
310
为什么我totalNum
的那么大?
解决方案
字典中有 5 个元素。您的值是 (12 + 42 + 1 + 6 + 1) = 62. 62*5 = 310。
每次浏览一个项目时,您都会获取所有 inventory.values() 的总和。如果您在循环中执行此操作,那么它应该是
totalNum = totalNum + v
如果你想在循环之外做,那么它应该是
def displayInventory(inventory):
for k, v in inventory.items():
print(v, k)
print("Total items of inventory: ")
return sum(inventory.values())
推荐阅读
- c# - 重新加载循环组件
- reactjs - 当我在 Link 中使用 `hreflang 属性时,我收到警告
- c# - 使用 Method 的 Generic T 创建具有相同 Generic T 的另一个对象的新实例
- computer-vision - 面对本次识别案例推荐OCR软件
- heroku - 为什么我在执行 Heroku CLI 命令时会出现这些错误?
- python - 如何使用 json 将编码的音频字符串传递给字节?
- javascript - 如何在javascript中测试两个具有不同参数值的返回函数?
- kubernetes - 使用 VS Code Kubernetes Extension 连接到外部集群
- python - 如何让玩家在pygame中进入下一个级别
- java - 重置 JDeveloper 的管理员密码 - WebLogic 集成服务器