python - 如何汇总列表中单个项目的总数?
问题描述
我一直在寻找一种方法来总结列表中的项目总数,但没有成功。使用 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,但我一直无法想出正确的方法来编写我的代码来达到那个答案。非常感谢!
解决方案
如果您还希望保持循环以显示项目,请使用此方法。在这里,您可以使用变量来跟踪总数,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))
推荐阅读
- javascript - 如何从另一个函数内部的firebase函数内部访问一个函数
- javascript - 如何分别添加每个内容的值并将它们全部添加?
- list - 如何列出使用组合框安装的 /dev/sda usb 存储
- forms - 如何在联系页面上添加“发送消息至”按钮?
- flutter - 没有为“FirebaseAuth”类定义方法“signInWithGoogle”
- ffmpeg - ffmpeg 字幕背景
- flutter - 从 Internet 获取嵌套数据
- jquery - 为什么在我的 MVC 应用程序中将输入框的 jQuery 设置值发布为 null 到我的控制器?
- python - Pandas - 将具有多列的多个系列转换为数据框
- python - pyfinance 模块。滚动 OLS - 需要最小窗口