首页 > 解决方案 > 来自 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的那么大?

标签: pythondictionary

解决方案


字典中有 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())

推荐阅读