python - 您如何汇总列表中的所有值并以有组织的方式打印最终项目及其最终值?
问题描述
问题: 编写一个程序来帮助您管理销售。它应该不断询问已售出的商品以及已售出的商品数量,直到输入空白商品。然后它应该打印出当天售出的每件商品的数量。
代码:
Items = {}
item = input('Item: ')
while item != '':
number = int(input('Number sold: '))
if item in Items:
Items[item] = Items[item] + number
else:
Items[item] = number
item = input('Item: ')
print('Total sales for today:')
for stuff in Items.values():
print(f'{item} : {stuff}')
这是代码,我在这里做的事情不会一次性打印所有最终值。
解决方案
错误
您的代码中的错误似乎在您的 for 循环中,因为我看不到变量item
在 f 字符串中的来源。因此,我建议您将 for 循环编写为:
for item in Items:
print(f'{item}: {Items[item]}')
推荐解决方案
既然你发布了一个问题,我想我也会给你一个解决这个问题的方法。使用模块defaultdict
中的并将其设置为为每个新键collections
提供默认值。0
from collections import defaultdict
my_dict = default_dict(lambda: 0)
这有助于您只需专注于添加新数量,而不必担心匹配键是否已经存在。
因此,新代码将如下所示:
from collections import defaultdict
def main():
items = defaultdict(lambda: 0)
while True:
item = input('Enter an item: ').lower()
if item == '':
break
quantity = int(input('Enter the quantity of the item: '))
items[item] += quantity
print('\n') # make the console output cleaner to look at
for item in items:
print(f'{item}: {items[item]}')
if __name__ == '__main__':
main()
推荐阅读
- python - 例外:@error:Gekko 中的最大方程长度
- wordpress - 即使用户重定向到正确的 url,kubernetes Ingress 仍显示“404 Not Found”
- azure - 为多租户应用添加服务主体时出错 - New-AzureADServicePrincipal:无法加载文件或程序集“RestSharp,版本=106.3.1.0,
- angular - TypeScript:创建数据访问层的最佳方式
- r - 如何在mutate中划分一列
- java - 如何创建嵌套的 JSONObject
- kotlin - 为什么 Kotlin 不能自动转换泛型类型
- spring - 如何在 SpEL 表达式中使用 Kotlin 的 `is` 运算符?
- regex - 使用正则表达式在包含数字的字符串中查找单词
- javascript - 在 Vue.js 中更新本地 JSON 文件