【问题标题】:Are there any ways to sum all the list values that are from dictionary?有什么方法可以对字典中的所有列表值求和吗?
【发布时间】:2021-01-17 10:10:29
【问题描述】:

我试图制作一个程序来总结我选择的所有价格。代码如下:

Menu_list = {"Cola" : 500,
             "Cheese" : 400,
             "Burger" : 1000,
             "Sprite" : 500,
             "Ice Cream" : 300}

Order_list = []

print(Menu_list)
while True:
    a = input()
    Order_list.append(Menu_list.get(a))
    print(sum(Order_list))
  1. 我想在我键入 Menu_list 中的菜单时执行 while 循环。如果不是,我想退出 while 循环并返回 Order_list 的总和。所以我尝试了“while a not in Menu_list”,但它不起作用。
  2. 我想从字典中获取特定值以列出并汇总所有列表值。但它会显示“TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'”。

这两个问题有什么解决办法吗?

【问题讨论】:

  • 您想在一个输入中选择所有选项吗?例如“奶酪、可乐、汉堡”。还是分开的?先是“奶酪”,然后是“可乐”,然后是“汉堡”?
  • 想在一个输入中选择所有选项。

标签: python typeerror


【解决方案1】:

这是可以解决问题的代码:

Menu_list = {"Cola" : 500,
             "Cheese" : 400,
             "Burger" : 1000,
             "Sprite" : 500,
             "Ice Cream" : 300}

Order_list = []

print(Menu_list)

a = "Start"

while a != "End":
    a = input()
    if a in Menu_list:
        Order_list.append(Menu_list[a])

    print("Sum of the list: {}".format(sum(Order_list)))
  1. 有时您需要结束 While 循环。这是通过检查输入来实现的 - fi 它的"End" 然后我们结束循环。

  2. 您还需要使用此语句if a in Menu_list:检查输入是否有效

【讨论】:

  • 感谢您的帮助!还有一个问题。 Order_list.append(Menu_list(a))。如果我使用(a)它将不起作用。为什么会这样?
  • 它是 dictionary 而不是 function。您必须使用["key"] 才能访问Value
  • 另外,如果答案有用,请投票,以便其他人可以看到它是有效的:)
  • 我投票了。但是“感谢反馈!声望低于 15 人的投票会被记录下来,但不要更改公开显示的帖子得分。”这弹出
【解决方案2】:

对于第一个问题:您需要将变量“a”设置为字典中的初始值。否则,while 循环根本不会执行。例如:

a = "Cola"
while a not in Menu_list:
...

对于第二个问题,如果 a 不在菜单列表中,请确保您的代码不会将价格添加到订单列表中,因为您的订单列表中没有。像这样:

if a in Menu_list:
    Order_list.append(Menu_list.get(a))

【讨论】:

    猜你喜欢
    • 2018-09-21
    • 2021-10-07
    • 2023-03-24
    • 2011-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多