首页 > 解决方案 > 如何汇总列表中单个项目的总数?

问题描述

我一直在寻找一种方法来总结列表中的项目总数,但没有成功。使用 ATBS 初学者 python 书。我的代码如下:

import pprint 
items = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12} 

print('Inventory:')

for item, inven_count in items.items():
    item_total = ???
    print(str(inven_count) + ' ' + item)

print('Total number of items: ' + str(item_total))

item_total 行是我不确定的。我知道我想要的答案是 62,但我一直无法想出正确的方法来编写我的代码来达到那个答案。非常感谢!

标签: pythonlist

解决方案


如果您还希望保持循环以显示项目,请使用此方法。在这里,您可以使用变量来跟踪总数,item_total += inven_count它是item_total = item_total + inven_count

import pprint 
items = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12} 

print('Inventory:')

item_total = 0

for item, inven_count in items.items():
    item_total += inven_count
    print(str(inven_count) + ' ' + item)

print('Total number of items: ' + str(item_total))

推荐阅读