【问题标题】:dictionary in python sum prices with 2 inputs带有2个输入的python总和价格字典
【发布时间】:2021-09-16 13:56:43
【问题描述】:

我有 2 个输入:

# The key is the available dates and the value is the price
a = {"g": 109192, "e": 116374, "o": 183368, "s": 162719}

# The dates that the user wants to take, this is going to be input by the user separeted by a space
b = ("g", "n", "e", "k", "s")

程序必须告诉用户日期的总费用以及可用的日期。

输出:

388285
g e s

到目前为止我的代码:

import json
a=input("")
b=list(input().split(' '))
dic=json.dumps(a)
def citas(dic,b):
  citas_disponibles=[]
  suma=0
  for dia in b:
    if dia in a:
      suma += a[dia]
      citas_disponibles.append(dia)
  return citas_disponibles
citas(dic,b)

但“suma”会产生“错误”

【问题讨论】:

  • 您的问题是什么? b = g n e k s 在 Python 中没有意义。
  • "b" 将由用户输入,我的意思是这样写,因为它将被空格分隔。

标签: python python-3.x python-2.7 dictionary dictionary-comprehension


【解决方案1】:
def give_date_pricesum(a,b):
    #assuming b is a list
    available_dates = []
    sum = 0
    for date in b:
        try:
            sum = sum + a[date]
            available_dates.append(date)
        except:
            print("date is not available")
    return sum,available_dates

所以基本上在代码中,我遍历了用户想要的日期列表,并根据我们的价格字典检查它们。每当需要的日期出现时,我们都会将其添加到总和中,最后返回总和和可用日期。
如果您想为多个用户运行它并想要更新字典,那么您需要删除从用户选择中选择的条目。为此,您可以使用del dictionary[key] 格式。

【讨论】:

    【解决方案2】:

    通过get 方法使用列表推导:

    In [1]: a={"g": 109192, "e": 116374, "o": 183368, "s": 162719}    
    In [3]: b = sum(a.get(i, 0) for i in "gneks")
    
    In [4]: b
    Out[4]: 388285
    

    【讨论】:

      猜你喜欢
      • 2019-06-13
      • 1970-01-01
      • 2014-11-16
      • 2018-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-11
      • 2012-07-26
      相关资源
      最近更新 更多