首页 > 解决方案 > 您如何汇总列表中的所有值并以有组织的方式打印最终项目及其最终值?

问题描述

问题: 编写一个程序来帮助您管理销售。它应该不断询问已售出的商品以及已售出的商品数量,直到输入空白商品。然后它应该打印出当天售出的每件商品的数量。

代码:

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}')

这是代码,我在这里做的事情不会一次性打印所有最终值。

输出应如下所示: 所需输出

虽然我的看起来像这样: 我的输出

标签: python

解决方案


错误

您的代码中的错误似乎在您的 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()

推荐阅读