python中的字典具有2个输入的总和价格

2024-09-28 01:33:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个输入:

# 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”会产生一个“错误”


Tags: thetoinjsoninputbyisdates
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
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]格式

相关问题 更多 >

    热门问题