python 中的字典用 2 个输入求和价格
dictionary in python sum prices with 2 inputs
我有 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”生成“错误”
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]
格式。
通过 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
我有 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”生成“错误”
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]
格式。
通过 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